java - Mockito NullPointerException on mocked object -


i have classes:

public class myclass(){     private logger logger;     @override    public void prepare(map map, topologycontext topologycontext, outputcollector outputcollector) {      this.collector = outputcollector;      logger = loggerfactory.getlogger(myclass.class);    }      @override     public void execute(tuple tuple) {         if (tuplehelpers.isticktuple(tuple)) {             logger.info("received tick tuple, triggering emit of current window counts");         emitcurrentwindowavgs();          } else {               ...         }     } } 

i want test mockito in way:

@runwith(mockitojunitrunner.class) public class myclasstest {   @mock  private logger logger;   @injectmock  private myclass myclass;   @test  public void mytest(){       tuple ticktuple = mocktuplehelpers.mockticktuple();       myclass myclass = new myclass();      // when     myclass.execute(ticktuple);      //     // verifyzerointeractions(collector);     verify(collector).emit(any(values.class)); 

}

however obtain nullpointerexception on logger.info("...").

i tried add donothing().when(logger).info(anystring()) result not change.

i searched in cases problem initialization of mocked object.

looking @ code, think have 2 problems, 1 being:

logger = loggerfactory.getlogger(intermediatestatisticsbolt.class); 

i assume overwrite mock if there (assuming, not see when prepare called).

the other in test, intantiate new myclass-object within test instead of using myclass-field populated mockito. suffices use myclass directly without instantiation. mockito , mockitojunitrunner take care of population.

depending on logging-framework may want consider logger-configuration dedicated testing. example, there exist @ least slf4j-test , slf4jtesting slf4j can assert logging statements if must.

if want keep mocked logger , don't want inject outside, may want use powermockito, or that. way can return mocking loggerfactory.getlogger-call. supplying way inject logger outside nicer using powermockito it.

the benefit of using logger-configuration dedicated testing not need adapt production code test works fine , can spare mocks (and training) again ;-)


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -