Question

I have following class

class MyClass{
   public void m(InputStream is){
       ...
       Parser eParser = getExcelFileParser();
       eParser.parse(is);
       ...
       eParser.foo();
       eParser.bar();

   }
   public ExcelFileParser getExcelFileParser(){
       ...
   } 
}

How to write unit test for method m at this situation? I want to mock eParser object only.

Is it possible?

I use Mockito and PowerMockito

Was it helpful?

Solution

You can do what you want in Mockito (no PowerMock needed) using a spy without changing your code at all.

In your unit test you need to do something like the following:

ExcelFileParser parser = mock(ExcelFileParser.class);
MyClass myClass = spy(new MyClass());
doReturn(parser).when(myClass).getExcelFileParser();

OTHER TIPS

Can you pass AnotherObject as a parameter into the method m rather than calling getAnotherObject() in the method itself?

Preface: I use EasyMock not Mockito so this may be a bit off.

Can't you create an inner subclass of MyClass in your test that overrides getExcelFileParser and has it return a mock? Like this:

public class MyClassMock extends MyClass {

     ExcelFileParser _mock;

     public MyClassMock(ExcelFileParser mock) {
          _mock = mock;
     }

     @Override
     public ExcelFileParser getExcelFileParser() {
         return _mock;
     }
}

I haven't tested this so there could be issues with this, but the basic idea should be right.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top