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();
Share:
11,116
gstackoverflow
Author by

gstackoverflow

Updated on June 04, 2022

Comments

  • gstackoverflow
    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 mock eParser object only.

    Is it possible?

    I use Mockito and PowerMockito

  • user1309663
    user1309663 about 10 years
    Then use Mockito to mock the getAnotherObject, eg when(myClass.getAnotherObject()).thenReturn(myNewMockObject)
  • geoand
    geoand about 10 years
    Yes! The spy only replaces the methods you tell.it to