标签: spring-test

如何使用MockMvc传递ModelAttrubute参数?

我有这个html spring形式:

<form:form action="addVacancy" modelAttribute="myVacancy">
        <form:label path="name">name</form:label>
        <form:input path="name" ></form:input>
        <form:errors path="name" cssClass="error" />
        <br>
        <form:label path="description">description</form:label>
        <form:input path="description" id="nameInput"></form:input>
        <form:errors path="description" cssClass="error" />
        <br>
        <form:label path="date">date</form:label>
        <input type="date" name="date" />
        <form:errors path="date" cssClass="error" />
        <br>
        <input type="submit" value="add" />
    </form:form>
Run Code Online (Sandbox Code Playgroud)

我通过这种方法处理这个表单:

@RequestMapping("/addVacancy")
    public ModelAndView addVacancy(@ModelAttribute("myVacancy") @Valid Vacancy vacancy,BindingResult result, Model model,RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            model.addAttribute("message","validation error");
            return new ModelAndView("vacancyDetailsAdd");
        }
        vacancyService.add(vacancy);
        ModelAndView mv = new ModelAndView("redirect:goToVacancyDetails");
        mv.addObject("idVacancy", vacancy.getId());
        redirectAttributes.addAttribute("message", "added correctly at "+ new Date());
        return mv;
    }
Run Code Online (Sandbox Code Playgroud)

如何提交相同的请求,这是在提交表单后获得的.这必须通过MockMvc完成.

@Test …
Run Code Online (Sandbox Code Playgroud)

java spring mocking spring-mvc spring-test

1
推荐指数
1
解决办法
5378
查看次数

如何使用SpringJUnit4ClassRunner使用RunNotifier或RunListener

我想在测试失败时收到通知.理想情况下,我想知道我的@After注释方法是否通过了测试.我知道它们是一个可以用于此目的的RunListener,但它只有在我们使用JunitCore运行测试时才有效.如果测试用例失败或类似于RunListener可以与SpringJUnit4ClassRunner一起使用,有没有办法得到通知?

java junit spring spring-test spring-junit

1
推荐指数
1
解决办法
738
查看次数

导入 Spring 的 ReflectionTestUtils 类时出现问题

我正在开发一个名为acme-platform的多模块 Maven 项目,模块设置如下:

  1. acme 管理
  2. acme-通用
  3. acme-全球
  4. acme服务
  5. acme-客户端
  6. acme-注册
  7. acme 属性
  8. acme测试

(它们在acme-platform pom中按此顺序列出。)

在某些模块中,我已经能够使用 Spring 的 ReflectionTestUtils 类。然而,在最后一个模块acme-test中,我确实想使用它,但我无法使用。acme-test pom中没有依赖项部分,因此我添加了一个。这是 pom:

<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)

http://maven.apache.org/xsd/maven-4.0.0.xsd">

<parent>
    <artifactId>acme-platform</artifactId>
    <groupId>com.awesomeness.acme</groupId>
    <version>1.21.0</version>
    <relativePath>../</relativePath>
</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>acme-test</artifactId>
<version>1.21.0</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
    </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

在添加依赖行之前,我无法将任何 Spring 的 api 导入到我的类中。导入这些行后,我能够访问大多数类,但不是全部,特别是 ReflectionTestUtils,即使它是 spring-test 模块的一部分(可以在此处验证)。

我正在使用 Intellij。我查看了其他问题(例如这个问题)的答案,以确保我正确更新了我的依赖项。无济于事。

有谁知道为什么我无法导入org.springframework.test.util.ReflectionTestUtilsacme -test? …

java spring intellij-idea spring-test maven

1
推荐指数
1
解决办法
5137
查看次数

如何销毁MockRestServiceServer?

我们使用RestTemplate来使用外部休息服务.我们的项目中有很多不同类型的服务,所有服务都使用不同的策略进行测试,比如模拟休息模板和模拟我们的通信对象.

我们在测试用例中使用了以下代码来使用MockRestServiceServer测试一个服务:

RestTemplate restTemplate = new RestTemplate();    
mockServer = MockRestServiceServer.createServer(restTemplate);
Run Code Online (Sandbox Code Playgroud)

所以我们的问题是:一旦这个测试用例完成,有没有办法销毁这个服务器,所以这不会影响其他测试用例?

rest unit-testing spring-test

1
推荐指数
1
解决办法
1565
查看次数

测试弹簧mvc休息控制器

我正在尝试使用MockMvcBuilders.standaloneSetup方法为spring mvc rest控制器创建一个非常基本的单元测试.我一直收到404错误.下面我列出我的测试应用程序上下文,我的测试类,我的控制器和完整的堆栈跟踪.任何指导表示赞赏.

@Configuration
public class TestContext
{
    @Bean
    public Service service()
    {
        return mock(Service.class);
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestContext.class})
@WebAppConfiguration
public class TestUsingWebAppContextSetUp
{
    private MockMvc mockMvc;

    @Autowired
    private Service service;

    @Before
    public void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(MyController.class)
                .build();
    }

    @Test
    public void test() throws Exception
    {
        mockMvc.perform(get("/search?phoneNumber=5551112222"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE));
    }
}

public class MyController
{
    @Autowired
    private Service service;

    @RequestMapping("/search")
    public List<SearchResult> search(@RequestParam(value="phoneNumber") String phoneNumber)
    {
        System.out.println("search called");
        Search search = new Search();
        search.setPhoneNumber(phoneNumber);
        return service.search(search);
    }
} …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-test spring-boot

1
推荐指数
1
解决办法
4506
查看次数

试驾Hystrix断路器配置

我们的应用程序是通过使用Hystrix实现断路器模式而以非常脆弱的方式编写的.

整个应用程序是使用测试驱动的实践创建的,但是我们需要通过在方法上配置相同的方法来实现断路器策略.

以下是我们使用的示例配置 -

@HystrixCommand(commandProperties = {
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "8"),
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "25"),
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")},
        fallbackMethod = "retrieveMapFallback")
Run Code Online (Sandbox Code Playgroud)

任何人都可以评论,如果有可用的功能或机会在我的集成测试中测试驱动它(它加载整个WebApplicationContext,因此知道应用程序可用的所有配置)?

或者,如果根本无法在我的应用环境中验证这一点?

任何输入都是有价值的.

tdd spring-test circuit-breaker hystrix spring-cloud-netflix

1
推荐指数
1
解决办法
4171
查看次数

如何在 JUnit 中模拟 System.getenv() [Powermock + Parameterized]

如何在 JUnit 中模拟“System.getenv("...")”。

目前我正在做:

@RunWith(Parameterized.class)
@PowerMockRunnerDelegate(PowerMockRunner.class)
@PrepareForTest(System.class)
public class TestClass extends BaseTest {

    public TestClass(String testCase) {
        this.testCase = testCase;
    }

    @Before
    @Override
    public final void initTable() throws Throwable {
        super.initTable();
        PowerMockito.mockStatic(System.class); 
        PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");       
    }
...
}
Run Code Online (Sandbox Code Playgroud)

我同时使用 PowerMock 和 Parameterizedrunner。

我得到以下异常行:

PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");
Run Code Online (Sandbox Code Playgroud)

例外:

org.mockito.exceptions.base.MockitoException: 
'afterPropertiesSet' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
    doThrow(exception).when(mock).someVoidMethod();
***
Run Code Online (Sandbox Code Playgroud)

spring-test junit4 mockito powermockito

1
推荐指数
1
解决办法
6750
查看次数

集成测试 - 无法打开 ServletContext 资源 /application/properties

我有2个.properties文件。一个是标准的,第二个是用于私人值的,例如电子邮件用户名、密码等......

集成测试抛出一个错误,说它无法打开 /application.properties

门户应用:

@SpringBootApplication(scanBasePackages = {"com.portal"})
@PropertySources({
        // global property file
        @PropertySource("application.properties"),
        // local property file that I store personal properties e.g.: mail username & password.
        @PropertySource("application-local.properties")
})
public class PortalApplication {

    public static void main(String[] args) {
        SpringApplication.run(PortalApplication.class, args);

    }
}
Run Code Online (Sandbox Code Playgroud)

如果我注释掉@PropertySources(),则测试运行。有没有办法在不发表评论的情况下运行集成测试@PropertySources()

错误:

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:107)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) …
Run Code Online (Sandbox Code Playgroud)

spring-test spring-boot

1
推荐指数
1
解决办法
4294
查看次数

是否可以在WebMvcTest中激活弹簧配置文件

给定一个类似的测试类:

@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest  {
... some tests
}
Run Code Online (Sandbox Code Playgroud)

我得到错误:

java.lang.IllegalStateException:配置错误:为测试类[com.example.MyControllerTest]找到了@BootstrapWith的多个声明:[@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.autoconfigure .web.servlet.WebMvcTestContextBootstrapper),@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]

理想的目标是我只是在运行控制器测试,因此出于测试性能的原因,不想设置整个上下文-我只需要“ Web层”。

我可以删除该@SpringBootTest(properties = "spring.profiles.active=test")行-但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义Web上下文,例如将不再应用的杰克逊自定义。有没有一种方法可以只对“ Web层”进行测试并仍然激活弹簧轮廓?

我的环境是java version "10.0.2" 2018-07-17,spring boot1.5.16.RELEASE

spring-test spring-test-mvc spring-boot spring-web spring-boot-test

1
推荐指数
1
解决办法
798
查看次数

真的,不可能对Spring Data JPA @Query进行单元测试吗?

首先,目标.什么是单元测试?单元测试是测试最小功能的测试,与测试更多的集成测试相反,例如:

  • 以任何方式或任何形式生成ApplicationContext的测试不是单元测试;
  • 触摸甚至意识到应用程序(标有@SpringBootApplication)类的测试不是单元测试;
  • 加载某些东西的src/main/resources测试不是单元测试
  • 从Spring Cloud Config服务器加载外部配置的测试绝对不是单元测试;
  • 存储库的单元测试不得启动(甚至不知道)web,mvc或安全问题.

那么,如何为Spring Data JPA存储库编写单元测试?(或者那么受欢迎和喜爱的框架不支持纯单元测试这样的事情吗?)

我的项目:Spring Cloud(云计算服务,安全OAuth2服务,尤里卡,zuul,身份验证,授权等)

让我们尝试测试最简单的存储库:

public interface StudentRepository extends CrudRepository<Student, Integer> {
    Optional<Student> findByStudentCode(Integer studentCode);
    Optional<Student> findTopByOrderByStudentCodeDesc();

    @Query(value = "SELECT COUNT(*) = 0 FROM t_student WHERE regexp_replace(LOWER(student_name), '\\s', '', 'g') = regexp_replace(LOWER(:suspect), '\\s', '', 'g')", nativeQuery = true)
    boolean isStudentNameSpeciallyUnique(@Param("suspect") String studentName);
}
Run Code Online (Sandbox Code Playgroud)

学生实体将具有:id,代码(自然ID),姓名,年龄.没什么特别的.这是测试.我们需要一个SUT(我们的存储库)和实体管理器来预填充SUT.所以:

@RunWith(SpringRunner.class)
@DataJpaTest // <-- loads full-blown production app context and fails!
public class StudentRepositoryTest {

    @Autowired
    TestEntityManager manager;

    @Autowired
    StudentRepository repository;

    @Test
    public void findByStudentCode_whenNoSuch_shouldReturnEmptyOptional() …
Run Code Online (Sandbox Code Playgroud)

unit-testing spring-test spring-data-jpa spring-boot spring-cloud

1
推荐指数
1
解决办法
1260
查看次数