piszę test case używając mockMVC w spring
to jest klasa którą testuję
@RestController
@Profile("http")
@RequestMapping(path = "/account")
@Api("/account")
public class AccountController {
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
@Autowired
private AccountService accountService;
@Autowired
public AccountController( AccountService accountService) {
this.accountService = accountService;
}
@PostMapping
@ApiOperation(value = "Add.", notes = "T")
public ResponseEntity<?> add(@Valid @RequestBody AccountDTO accountDTO) {
return addAccountService.retreiveName(accountDTO.getName())
.map(accountExist -> ResponseEntity.status(HttpStatus.CONFLICT).build()).orElseGet(() -> {
AddAccounrDTO add = addaccountService.addaccount(accountDTO);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest().path("/" + add.getId()).build().toUri();
return ResponseEntity.add(location).build();
});
}
Moja metoda testowa:
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest(classes={ Application.class })
@ContextConfiguration
public class AccountControllerTest {
private MockMvc mockMvc;
@Mock
private AddAccountService addaccountService;
@InjectMocks
private AccountController accountController;
@Autowired
WebApplicationContext context;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
Test
public void createAccount() throws Exception {
AccountDTO accountDTO = new AccountDTO("SAVINGS", "SAVINGS");
CreatedAccountDTO createdAccountDTO = new CreatedAccountDTO("SAVINGS","SAVINGS", 0);
when(addaccountService.findByName("SAVING")).thenReturn(Optional.empty());
when(addaccountService.createAccount(any())).thenReturn(createdAccountDTO);
mockMvc.perform(
post("/account").contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(AccountNewDTO)))
//.content("{ \"name\": \"SAVINGS\", \"email\": \"SAVINGS\"")
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(header().string("location", containsString("/account/0")))
.andReturn();
//.andExpect(jsonPath("$.content", hasSize(1)))
//.andExpect(jsonPath("$.name", Matchers.equalTo("Saved")))
//andExpect(jsonPath("$.email", Matchers.equalTo ("Saved")));
//.andExpect( jsonPath( "$.content", Matchers.containsString( "Wandel der Bildungsvorstellungen" ) ) );;
}
public static String asJsonString( final Object obj){
try {
final ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Test case status failed z następującym error: java.lang.AssertionError: Status
Po wykonaniu testu otrzymuję
java.lang.AssertionError: Expected :201 Actual :404
Jak mogę to naprawić ? ? Jaki jest błąd ?
Annotation @SpringBootTest zakomentowane, ponieważ uruchomienie testu z tym daje błąd java.lang.IllegalStateException: Failed to load ApplicationContext - java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:107)