Mockito: How can I mock the logger found using the @Slf4J

Viewed 1428

Is there a way to mock the logger found in @Slf4j without using powermock? When using this annotation it creates a logger like this

private static final Logger log = LoggerFactory.getLogger(Sample.class);

I know standard mockito does not support static mocking so I am trying to find a way to refactor so that it becomes non static. I want the logger to work like the default @Slf4j logger works in normal use but in the tests I just want the logger to do nothing when called.

This is what I am trying to get my test class to look like.

    @ActiveProfiles("test")
    @RunWith(SpringRunner.class)
    @SpringBootTest
        public class SampleTest {
            @Mock
            //This is where I want my logger to be mocked
            Logger log;

            Sample sample;

        @Before
        public void setup(){
            MockitoAnnotations.initMocks(this);
            doNothing.when(log.debug(anyString()));
    }

Any insight will be greatly appreciated.

2 Answers

I don't think you can do this, since Lombok is injecting the code at compile time and Mockito mocks at runtime.

If you only want to log messages to go away, you can set the log-level accordingly in application-test.properties or application-test.yml. The logger would still be there but do nothing (almost).

Related