您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

无法针对REST层运行单元测试

无法针对REST层运行单元测试

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

@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项目中运行,因为根据@SpringBoot文档,项目的主类使用@SpringBoot进行了注释

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

由于JHipster需要的配置不仅仅是认配置,因此JHipster并未使用@SpringBootApplication,正如您在项目中看到的那样。完全可以,并且没有问题。

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

其他 2022/1/1 18:13:33 有858人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶