使用MockMvc对控制器进行单元测试时,如何捕获logger.error消息?

时间:2019-10-14 19:44:31

标签: java spring-boot unit-testing logging mockito

我有一个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的情况吗?

0 个答案:

没有答案