0
public void someMethod(Object obj) {
  ObjectMapper o = new ObjectMapper ();
  logger.info(o.writeValueAsString(obj));
}

I don't understand how to write test case for this. I am using Apache log4j logger And writing test case in mockito with spring boot

How to mock log when I have code like

class Someclass {

  Logger logger= LoggerFactory.getLogger(Someclass);
  //Some code and methods
}

Test class

class SomeclassTest{
  ...
  ...

  Logger logger;

  @Before {
  public void setup () {

  Mockito.when
    (LoggerFactory.getLoggers(Matchers.any(Class.class)))
   .thenReturn(logger);
  }
  ...
  ...
}
tkruse
  • 10,222
  • 7
  • 53
  • 80
Srth
  • 1
  • 1
  • 4
    You inject a mock logger, you call your method, then you verify that info() has been called on your mock logger. But first, you fix the compilation errors, and you indent your code. – JB Nizet Aug 05 '18 at 05:55
  • Correct but how can I mock the logger object. I have added a code in question for a reference – Srth Aug 06 '18 at 05:53
  • 1
    You won't be able to mock it with Mockito if you get it from a static method call thi way. Either use PowerMockito (can't help there), or inject it with Spring, or don' test your logs (do you really need to test that?) – JB Nizet Aug 06 '18 at 06:20
  • Unfortunately yes... I have tried to mock it but I am not able to do it'. I have added the code which I try – Srth Aug 06 '18 at 06:41
  • You won't be able to mock it with Mockito if you get it from a static method call this way. Either use PowerMockito (can't help there), or inject it with Spring. – JB Nizet Aug 06 '18 at 06:41
  • How can I inject it in spring?? Could you please explain or show some example if possible – Srth Aug 06 '18 at 06:48
  • You define a Logger as a spring bean, with a`@Bean`-annotated method of a configuration class, and you inject it like any other bean. – JB Nizet Aug 06 '18 at 06:51
  • @JBNizet _"do you really need to test that?"_ <- asking the important questions :) – Phil Aug 06 '18 at 06:52
  • Related: https://stackoverflow.com/questions/1827677 – tkruse Aug 08 '18 at 09:26
  • Possible duplicate of [How to do a JUnit assert on a message in a logger](https://stackoverflow.com/questions/1827677/how-to-do-a-junit-assert-on-a-message-in-a-logger) – tkruse Aug 08 '18 at 09:34

0 Answers0