0

I need to mock a Logger in a @Service class to make tests. I want to verify if a logger message will be created. (SLF4J Logger)

I think I can do it using @Bean class and make the Logger a managed bean on spring.

But I need to create the logger using the .class of the injected Service too.

Somebody knows how to do it?

Nathan, thanks by the duplicate tag and suggestuse appender.

My problem is i cannot use a unit test or a test without spring-context, because I have to do a integration-test with two DBs.

And the test for spring does not allow mock the logger in a first test without influences the next test.

Example:



    @Service
    class MigrateDataService{
       @Autowired private FirstDB firstDB;
       @Autowired private SecondDB secondDB;

       Logger logger = LoggerFactory.getLogger(MigrateDataService.class);

       @Transactional(...)
       public void migrate(){

          Data data firstDB.getData();

          if(data.isWarn()){
                logger.warn("Data {} is warning", data);
          }

          secondDB.save(data);
       }
    }

I need to detect the logger.warn call.

thanks...

  • help us help you - share the (relevant parts of) your code. – Mureinik Mar 22 '19 at 13:26
  • The duplicate target has both mockito-specific answers and advice on adding an appender to the log so that the expected message can be found in the appender. – Nathan Hughes Mar 22 '19 at 13:38
  • Nathan, thanks by the duplicate tag and suggestuse appender. My problem is i cannot use a unit test or a test without spring-context, because I have to do a integration-test with two DBs. And the test for spring does not allow mock the logger in a first test without influences the next test. – Marcos Côrtes Mar 23 '19 at 20:23
  • As far as I understand, you want to get rid of 2 things at once, which in this case isn't any good. You should consider testing your Service including Logging-Functionality separately. Then you can test your Integration without problems of the Logger – gkhaos Mar 24 '19 at 12:22
  • @moneydhaze, i suspected it. I will try make another test (unit) for logger.... – Marcos Côrtes Mar 24 '19 at 17:37
  • So with your update I'm even more sure that this belongs into the unit test of the Service. However I wonder if it's really the log you want to test... I guess that you want to check if you log something as approval that something happened, which is a nice workaround for testing, but not the purpose. – gkhaos Mar 24 '19 at 18:36

1 Answers1

0

This is not a slick way to do it but it works.

private void setLogger(Logger logger){
    this.logger = logger;
}

then in your test code, set the logger to the mocked logger.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68