如何正确使用Spring Boot测试?

时间:2018-07-15 20:08:54

标签: java spring spring-boot spring-test

我不太了解如何正确使用Spring中的测试。我真的需要执行整个Spring配置的完整初始化才能运行测试吗?

我有一个最终集成测试,一个正常的控制器调用,并检查其响应。我必须这样做:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RestControllerTest {
    @Autowired
    HomeRestController homeRestController;
    @Test
    @Repeat(value = 15)
    public void test() throws Exception {
        RequestSearch requestSearch = new RequestSearch();
        HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
        requestSearch.setMonth(7);
        requestSearch.setYear(2018);
        requestSearch.setGbNumber(5010);
        requestSearch.setPayTime(new Double(32));
        requestSearch.setScanTime(new Double(2.7));
        requestSearch.setWaitTime(new Double(35));
        ReportResponse reportResponse = homeRestController.find(requestSearch, httpServletResponse);

        Assert.assertTrue(reportResponse.cashBoxPlans.size() == 1487);
        Assert.assertTrue(reportResponse.getExcelPath().equals("ExceReport.xls"));

    }
}

查看了Spring文档后,我找到了一个完美的示例,并想在测试中添加一个单独的类:

@RunWith(SpringRunner.class)
@WebMvcTest(HomeRestController.class)
public class RestControllerMockTest {
    @Autowired
    private MockMvc mvc;
    @Test
    public void test() throws Exception {
        RequestSearch requestSearch = new RequestSearch();
        requestSearch.setMonth(7);
        requestSearch.setYear(2018);
        requestSearch.setGbNumber(5010);
        requestSearch.setPayTime(new Double(32));
        requestSearch.setScanTime(new Double(2.7));
        requestSearch.setWaitTime(new Double(35));
        mvc.perform(post(HomeRestController.postUrl,requestSearch).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());    
    }
 }

但是此测试不起作用,这是抛出的异常:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [ru/denisa/configuration/SQLServerDatabaseConfiguration.class]: 

异常(SQLServerDatabaseConfiguration)中提到的配置类是带有@Configuration注释的配置类。

如果我在测试中添加以下注释:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

然后我得到以下异常:

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [ru.denisa.test.service.rest.RestControllerMockTest]:

如何正确执行?谢谢!

2 个答案:

答案 0 :(得分:1)

尝试一下。

0

答案 1 :(得分:1)

一些简单的代码:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HomeRestController.class)
public class RestControllerMockTest {

}

PS。要禁用安全性,只需更改@WebMvcTest(controllers = HomeRestController.class, secure= false)