0

I have simple web-application. I have validations on my fields. And It work correct. When I'm tried to input incorrect value I get a mistake in browser. But now I'm writing Integration test and want to write test with wrong parameters. And this test doen't work. My BindingResult got wrong param (ApartmentNumber should be more than 0), but it doesn't find a mistake. My entity class:

public class Apartment {

private Integer apartmentId;

@Min(value = 1, message = "Apartment number should be more than 0")
@Max(value = 1000, message = "Apartment number should be less than 1001")
@NotNull(message = "Apartment number is a required field")
private Integer apartmentNumber;

@NotBlank(message = "Apartment class is a required field")
private String apartmentClass;

getters and setters. My controller:

    @PostMapping(value = "/apartment")
public String addApartment(@Valid @ModelAttribute("apartmentAttribute") Apartment apartment, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "apartmentPage";
    }
    LOGGER.debug("addApartment({})", apartment);
    apartmentService.create(apartment);
    return "redirect:/apartments";
}

My test:

 @Test
    public void shouldAddingNewApartmentWithWrongParam() throws Exception {
        mockMvc.perform(
                MockMvcRequestBuilders.post("/apartment")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .param("apartmentNumber", String.valueOf(-10))
                        .param("apartmentClass", "SomeWord")
        ).andExpect(status().is3xxRedirection())
                .andExpect(view().name("/apartmentPage"));
    }

And when I debug this test, I got 0 erros and this line in BindingResult:

Apartment{apartmentId=null, apartmentNumber=-10, apartmentClass='SomeWord'}

Why does it happen? Why doens't BindingResult find an error? How I should write this test?

I added the begining of the test class:

@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext-test.xml"})
@Transactional
public class ApartmentControllerTest {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Autowired
private ApartmentService apartmentService;

@Autowired
private ApartmentDtoService apartmentDtoService;

@BeforeEach
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
Vitaliy
  • 25
  • 7

0 Answers0