Я хочу протестировать контроллер Spring Boot API со структурой классов, как показано ниже:
Контроллер:
@RestController
@RequestMapping("/member-management")
@Validated
public class MemberManagementController {
private final MemberManagementService memberManagementService;
public MemberManagementController(MemberManagementService memberManagementService) {
this.memberManagementService = memberManagementService;
}
@GetMapping(value = "/view-member")
public ResponseEntity<?> viewMember(
@NotBlank(message = "username must not be blank!!")
@Size(max = 20, message = "maximum size of username id is 20!!")
@RequestParam("username") String username) {
...
}
...
Рекомендации контроллера:
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Object> handleConstaintViolatoinException(final ConstraintViolationException ex) {
List<String> details = new ArrayList<>();
Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
details.add(violation.getMessage());
}
ApiErrorResUtil error = new ApiErrorResUtil(String.valueOf(HttpStatus.BAD_REQUEST.value()),
"Request param error", details);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
...
}
Юнит-тест:
@RunWith(MockitoJUnitRunner.class)
public class MemberManagementControllerTest {
@InjectMocks
private MemberManagementController memberManagementController;
@Mock
private MemberManagementService memberManagementService;
private MockMvc mockMvc;
@Before // Execute before each test method
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(memberManagementController)
.setControllerAdvice(new CustomRestExceptionHandler()) // add ControllerAdvice to controller test
.build();
}
@Test
public void viewMember_usernameSizeExceedsMaximumLimit() throws Exception {
// Value from client
String username = "a12345678901234567890"; // 21 characters
MemberResDtoDataDummy memberResDtoDataDummy = new MemberResDtoDataDummy();
when(memberManagementService.viewMember(username)).thenReturn(memberResDtoDataDummy.getMember1());
mockMvc.perform(get("/member-management/view-member").param("username", username))
.andExpect(status().isBadRequest()).andReturn();
}
Проблема:
java.lang.AssertionError: Status expected:<400> but was:<200>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
...
Может кто-нибудь помочь мне решить эту проблему, почему ожидаемый статус равен 200 вместо 400, другие тесты метода запроса POST, PUT, PATCH, DELETE с неверно введенным параметром все еще работает нормально: (