Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock local variable obtained from another method of tested class?

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

like image 309
gstackoverflow Avatar asked Nov 27 '25 07:11

gstackoverflow


1 Answers

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();
like image 51
geoand Avatar answered Nov 28 '25 20:11

geoand