如何在ResponseEntityExceptionHandler @ControllerAdvice中模拟服务

时间:2018-07-04 12:23:38

标签: unit-testing spring-boot spring-test spring-boot-test spring-mvc-test

我有Controller

@RestController
@RequestMapping("/api/users")
public class UserController {

  private final UserService userService;

  @Autowired
  public UserController(UserService userService) {
    this.userService= userService;
  }

  @PostMapping(value = "/login")
  public UserDto login(@RequestBody UserDto user) {
    return userService.getUserWithAuth(user);
  }
}

我有ControllerAdvice

@Slf4j
@ControllerAdvice
public class ExceptionHandlerAdvice extends ResponseEntityExceptionHandler {

  private final ErrorMessagesService errorMessagesService;

  @Autowired
  public ExceptionHandlerAdvice(ErrorMessagesService errorMessagesService) {
    this.errorMessagesService = errorMessagesService;
  }


  @ExceptionHandler(SomeException.class)
  protected ResponseEntity<RestResponse<RestResponse.RestError>> handleSomeException(SomeException e) {
    ErrorMessage messages = errorMessagesService.findByCode(e.getCode());
    RestResponse.RestError restError = new RestResponse.RestError(e.getCode(), formatErrorMessage(messages));
    return ResponseEntity.ok().body(new RestResponse<>(restError, null));
  }
}

然后我为控制器编写UnitTest:

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @MockBean(name = "mockUserService")
  private UserService userService;

  private UserDto userDtoResponse;
  private UserDto userDtoRequest;

  @Before
  public void init() {

    cashierDtoRequest = new UserDto();
    userDtoRequest.setLogin("Test");
    userDtoRequest.setPassword("Test");

    userDtoResponse= new UserDto();
    userDtoResponse.setLogin("Test");
    userDtoResponse.setPassword("Test");
    userDtoResponse.setAuthToken("123");

    when(userService.getUserWithAuth(userDtoRequest)).thenReturn(userDtoResponse);
  }

  @Test
  public void shouldReturnDefaultMessage() throws Exception {
    mockMvc.perform(post("/api/user/login")).andDo(print()).andExpect(status().isOk())
      .andExpect(jsonPath("$.login").value(userDtoResponse.getLogin()))
      .andExpect(jsonPath("$.authToken").value(userDtoResponse.getAuthToken())));
  }

但是当我开始测试时,我得到了异常:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'mypackeg.ErrorMessagesService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

1 个答案:

答案 0 :(得分:0)

尝试通过使用注释选项来排除在cd platforms/android ./gradlew clean 中创建bean的情况

@WebMvcTest