How to mock local variable obtained from another method of tested class?
11,116
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();
Author by
gstackoverflow
Updated on June 04, 2022Comments
-
gstackoverflow almost 2 years
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 mockeParser
object only.Is it possible?
I use Mockito and PowerMockito
-
user1309663 about 10 yearsThen use Mockito to mock the getAnotherObject, eg when(myClass.getAnotherObject()).thenReturn(myNewMockObject)
-
geoand about 10 yearsYes! The spy only replaces the methods you tell.it to