Как мне издеваться над CustomLogger и LogUtil, чтобы сдать мой тест?Я уже издевался над ними в моем тестовом классе, но, похоже, это не считается.
Пожалуйста, обратитесь к моим 2 комментариям, начинающимся с 'ТЕСТ (1 и 2)'.Если я раскомментирую ОБА из них, тест пройден.
Похоже, что издевательство распознается при достижении контроллера, но дальше, когда вызываются другие классы, оно больше не считается.
// TEST CLASS
@InjectMocks
private MyController controller;
@Mock
private LogUtil logUtil;
@Mock
private CustomLogger logger;
@Mock
private ConfigurationService configService;
private MockMvc mockMvc;
@Test
public void testMyException() throws Exception {
when(configService.getConfiguration(anyString()))
.thenThrow(new ConfigurationException(""));
mockMvc.perform(
get("/api/some/bad").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().string(""))
.andExpect(
status().reason(
"Invalid parameter in Request"));
}
//CONTROLLER CLASS
@Autowired
ConfigurationService configService;
@Autowired
private CustomLogger logger;
@RequestMapping(value = "api/some/{argument}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
SomeConfiguration getAllInfo(@PathVariable String argument,
HttpServletRequest request, HttpServletResponse response) {
try {
SomeConfiguration configuration = configService.getConfiguration(argument);
logger.doSomething();
return configuration;
} catch (ConfigurationException e) {
logger.doSomething(); // no issue here
throw new CustomException("config error", e); // after reaching here, we go to ControllerAdvice's badRequestErrorHandler
}
}
//ADVICE MANAGING EXCEPTIONS
@ControllerAdvice
public class GlobalExceptionHandlingControllerAdvice {
@Autowired
private LogUtil logUtil;
@Autowired
private CustomLogger logger;
@ExceptionHandler(CustomException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Invalid parameter in Request")
public void badRequestErrorHandler(HttpServletRequest request, HttpServletResponse response) {
// LogUtil logUtil = new LogUtil(); // TEST Will pass if I uncomment this (1)
logUtil.logFail(request, "BAD REQUEST");
}
}
//LOG UTIL CLASS
@Component
public class LogUtil {
@Autowired
private CustomLogger logger;
public void logFail(HttpServletRequest request, String errorMsg){
// CustomLogger logger = new CustomLoggerImpl(); // TEST Will pass if I uncomment this (2)
logger.doLogging();
}
}
РЕДАКТИРОВАТЬ: Попытка добавить следующее в мой метод испытаний, который не имеет значения.
private GlobalExceptionHandlingControllerAdvice advice = new GlobalExceptionHandlingControllerAdvice ();
doNothing().when(logUtil).logFail(any(HttpServletRequest.class), anyString());
doNothing().when(logger).setFieldValue(anyString(), anyString());
doNothing().when(advice).badRequestErrorHandler(any(HttpServletRequest.class), any(HttpServletResponse.class));