【问题标题】:Cannot run Unit Tests against REST layer无法针对 REST 层运行单元测试
【发布时间】:2018-08-05 04:10:42
【问题描述】:

我无法使用 jhipster (according to spring gs guides) 对 Web 层进行单元测试:

@RunWith(SpringRunner.class)
@WebMvcTest
public class FlightControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private FlightService flightService;

    @Test
    public void testCreate() throws Exception {

        FlightDto expected = new FlightDto();
        ReflectionTestUtils.setField(expected, "id", 1L);

        when(flightService.createFlight(any(FlightDto.class))).thenReturn(expected);

        FlightDto flightDto = new FlightDto();
        flightDto.setNumber("CAI-123400");

        this.mockMvc.perform(post("/api/flight")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(flightDto)))
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(header().string("Location", endsWith("/api/flight/1")));
    }

}

上面的单元测试在绿地spring boot project的情况下成功,但在green-field spring boot-based jhipster project的情况下失败:

当我在 FlightResource 的 jhispter 项目 (springboot-with-jhipster) 中运行单元测试时,我得到了:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:202)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:137)
    at org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:35)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:409)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:323)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:277)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:112)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:82)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
    at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

【问题讨论】:

    标签: spring spring-boot junit jhipster


    【解决方案1】:

    我可以使用以下代码运行测试:

    @RunWith(SpringRunner.class)
    
    //@WebMvcTest remove @WebMvcTest
    //add SpringBootTest
    @SpringBootTest(classes = JhUnittestRestApp.class)
    public class FlightResourceTest {
    
        //@Autowired remove anotation
        private MockMvc mockMvc;
    
        @MockBean
        private FlightService flightService;
    
        @Autowired
        private MappingJackson2HttpMessageConverter jacksonMessageConverter;
    
        @Autowired
        private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
    
        @Autowired
        private ExceptionTranslator exceptionTranslator;
    
        @Before
        public void setup() {
            //initialize the bean
            MockitoAnnotations.initMocks(this);
            final FlightResource flightResource = new FlightResource(flightService);
            this.mockMvc = MockMvcBuilders.standaloneSetup(flightResource)
                .setCustomArgumentResolvers(pageableArgumentResolver)
                .setControllerAdvice(exceptionTranslator)
                .setConversionService(createFormattingConversionService())
                .setMessageConverters(jacksonMessageConverter).build();
        }
    
        @Test
        public void testCreate() throws Exception {
    
            FlightDTO expected = new FlightDTO();
            ReflectionTestUtils.setField(expected, "id", 1L);
    
            when(flightService.save(any(FlightDTO.class))).thenReturn(expected);
    
            FlightDTO flightDto = new FlightDTO();
            flightDto.setNumber("CAI-123400");
            //update the url to /api/flights so that the test can pass 
            this.mockMvc.perform(post("/api/flights")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(flightDto)))
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(header().string("Location", endsWith("/api/flights/1")));
        }
    
    }
    

    您的 FlightControllerTest 正在您的 springboot-no-jhipster 项目中工作,因为 project is annotated with @SpringBoot 的主类根据 documentation of @SpringBoot

    The @SpringBootApplication annotation is equivalent to using:
    @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes
    

    由于 JHipster 需要比默认配置更多的配置,因此 JHipster 没有像 see in your project 那样使用 @SpringBootApplication。这完全没问题,可以正常工作。

    另一方面,您的测试的错误消息是说它无法检测到@SpringBootConfiguration。还有其他注释,例如@ContextConfiguration 或 @SpringBootTest 是用于测试的 rocomandet。实际上,主配置类中的哪些注释与测试注释匹配存在一些不一致之处,请参见herehere

    【讨论】:

    • 所以它是加载整个 Spring 应用程序(如在常规集成测试中),但模拟 Controller 依赖项,对吗?而且这是唯一的选择?
    • 既然“条条大路通罗马”,可能还有其他方法可以做到这一点。为了使用注释 RunWith(SpringRunner.class) 和 WebMvcTest 运行您的测试,您需要使用注释 ContextConfiguration。 ContextConfiguration 的问题是在 JHipster 项目中更难配置,因为配置分布在不同的模块中。对我来说,JHipster 提供的 IntegrationTest 工作得非常好
    • 你知道,仅仅运行一个 UNIT 测试需要太长时间,它应该运行得更快!
    • 目前我没有时间深入了解如何配置它以按照您的意愿运行。我同意你的单元测试应该很快。要获得解决方案,将更深入地了解 WebMvcTest-annotation 对 SpringBootApplication-annotation 之外的默认值的期望。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多