我可以使用以下代码运行测试:
@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可以用于测试的。实际上,主配置类中的注释与测试注释之间存在一些不一致之处,请参见此处或此处。