2

I have a Spring Boot app and I need to verify that whenever a request failed (different from 200) system logs the status code and message. So far, I cannot find a way to verify logger. Is there any way to do it with Mockito?

MyControllerTest code:

@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 code:

@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);
        }
    }
}

I made research and one of the possible solutions would be through Spy or through changing modifiers to public. Both solutions are not applicable to my current configuration.

Is there anything else I miss that can help me verify logger content or, at least, if logger was called?

Dmytro Chasovskyi
  • 3,209
  • 4
  • 40
  • 82
  • 1
    Take a look at [this answer](https://stackoverflow.com/a/30703932/8629960), but be aware that this will change the entire class – Kirill Simonov Oct 14 '19 at 21:29
  • Probably duplicate of https://stackoverflow.com/q/4650222/8547799 – Tns Oct 17 '19 at 10:23
  • @Tns sibling but not duplicate because I also want to have the correct `Controller` behavior which more as sibling/extension to the question you mentioned. I have a [correlated question](https://stackoverflow.com/questions/58401388/how-to-enforce-mockitojunitrunner-fail-without-basic-http-authentication). – Dmytro Chasovskyi Oct 17 '19 at 11:36

0 Answers0