Reputation: 635
Spring Boot here. I currently have the following 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);
}
}
I would like to write an integration test for it that:
FizzbuzzController
(under test) with a mocked FizzbuzzService
or the real thing; andMy best attempt thus far:
@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);
}
}
When I run this, the test fails to run and it is clear (looking at the logs) that Spring is loading the entire application context of my app, whereas I just want it to isolate the context to this test class, the main FizzbuzzController
class, and anything in the dependency tree underneath it.
Can anyone spot where I'm going awry?
Upvotes: 1
Views: 1908
Reputation: 2699
You need another context for testing. I'm suggesting you to have a separate Test config:
@TestConfiguration
@Slf4j
@EnableJpaRepositories("tth.patientportal.repository")
public class TestConfig { // bean configs goes here for testing if you need to change
// context}
and in a controller test build the context like below:
@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());
}
}
Upvotes: 2