java - Mocking and verifying SLF4J with JMockit -


i have class slf4j logger instanced like:

 public class myclass {      private static final logger log = loggerfactory.getlogger(myclass.class);      public void foo() {       log.warn("my warn");     }   } 

and need test jmockit like:

 @test  public void shouldlogwarn(@mocked logger log) throws exception {    new expectations() {{      log.warn(anystring);    }};    myclass = new myclass();    my.foo();   } 

after searching lot figured out, need use mockup somehow. can't how exactly.

btw, i'm using last version of jmockit(1.29) no more can setfield(log) final static fields.

jmockit has @capturing annotation works situation.

indicates mock field or mock parameter classes extending/implementing mocked type mocked.

future instances of capturing mocked type (ie, instances created sometime later during test) become associated mock field/parameter. when recording or verifying expectations on mock field/parameter, these associated instances regarded equivalent original mocked instance created mock field/parameter.

this means if annotate @capturing instead of @mocked, every logger created during test run associated 1 annotated. following works:

 @test  public void shouldlogwarn(@capturing final logger log) throws exception {    // ought verifications block instead    new expectations() {{      log.warn(anystring);    }};    myclass = new myclass();    my.foo();   } 

as side note, if want verify method called, it's better use verifications instead, since intended for. code this:

 @test  public void shouldlogwarn(@capturing final logger log) throws exception {    myclass = new myclass();    my.foo();     new verifications() {{      log.warn(anystring);    }};  } 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -