简体   繁体   中英

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

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();

您可以将 AnotherObject 作为参数传递给方法 m 而不是在方法本身中调用 getAnotherObject() 吗?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM