[英]Spring Boot controller test loading entire application context
Spring 在此处启动。 我目前有以下REST controller:
@RestController
public class FizzbuzzController {
private final FizzbuzzService FizzbuzzService;
public FizzbuzzController(FizzbuzzService FizzbuzzService) {
this.FizzbuzzService = FizzbuzzService;
}
@PostMapping("/Fizzbuzzs/{fizzbuzzId}")
public ResponseEntity<FizzbuzzDTO> addFizzbuzz(@RequestParam("files") List<MultipartFile> files,
@PathVariable String fizzbuzzId) throws IOException {
FizzbuzzDTO fizzbuzzDTO = fizzbuzzService.store(files, fizzbuzzId);
return ResponseEntity.status(HttpStatus.OK).body(fizzbuzzDTO);
}
}
我想为它编写一个集成测试:
FizzbuzzService
或真实的东西注入FizzbuzzController
(正在测试); 和迄今为止我最好的尝试:
@WebMvcTest(FizzbuzzController.class)
@EnableConfigurationProperties
@AutoConfigureMockMvc
public class FizzbuzzControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private FizzbuzzService FizzbuzzService;
@Test
public void should_store_fizzbuzz_files() throws Exception {
// I can't even get the test to run
assertTrue(1 == 1);
}
}
当我运行它时,测试无法运行并且很明显(查看日志)Spring 正在加载我的应用程序的整个应用程序上下文,而我只是希望它隔离这个测试 class 的上下文,主FizzbuzzController
ZA2F2ED4F8EBC2ABCB4ZDC2 ,以及它下面的依赖树中的任何内容。
谁能发现我哪里出错了?
您需要另一个上下文进行测试。 我建议你有一个单独的测试配置:
@TestConfiguration
@Slf4j
@EnableJpaRepositories("tth.patientportal.repository")
public class TestConfig { // bean configs goes here for testing if you need to change
// context}
并在 controller 测试中构建如下上下文:
@RunWith(SpringRunner.class)
@AutoConfigureTestEntityManager
@SpringBootTest
@TestPropertySource("classpath:application-unittest.properties")
@ContextConfiguration(classes = {TestConfig.class})
public class RestControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup()
{
mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void shouldReturnRegisteredUser() throws Exception {
this.mockMvc.
perform(MockMvcRequestBuilders
.post("url")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").exists());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.