我有一个Spring Boot
应用程序,我需要验证每当请求失败(与200
不同)时,系统都会记录状态代码和消息。到目前为止,我找不到验证logger
的方法。有没有办法用Mockito
做到这一点?
MyControllerTest
代码:
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(locations = "classpath:application-test.yml")
public class MyControllerTest {
private MockMvc mockMvc;
@Mock
private RestTemplate localRestTemplate;
@InjectMocks
private MyController myController;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
}
@Test
public void test() throws Exception {
given(localRestTemplate.getForEntity("/test", String.class))
.willReturn(new ResponseEntity<>("Unsupported media type", HttpStatus.UNSUPPORTED_MEDIA_TYPE));
mockMvc.perform(get(MY_URL))
.andExpect(status().isOk());
}
}
MyController
代码:
@RestController
@RequestMapping(value = "/my/url")
public class MyController {
protected final static Logger logger = LoggerFactory.getLogger(MyController.class);
private final RestTemplate localRestTemplate;
@Autowired
public MyController(RestTemplate localRestTemplate) {
this.localRestTemplate = localRestTemplate;
}
@Scheduled(cron = "-")
@GetMapping(path="/report")
public void getReport() {
try {
localRestTemplate
.getForEntity("/test", String.class);
} catch (RestClientException e) {
logger.error("Couldn't trigger report generation!", e);
}
}
}
我进行了研究,可能的解决方案之一是通过Spy
或将修饰符更改为public
。这两种解决方案均不适用于我当前的配置。
我还有其他想念的内容,可以帮助我验证logger
的内容,或者至少是如果调用了logger
的情况吗?