How to mock a call of an inner method from a Junit

自闭症网瘾萝莉.ら 提交于 2020-01-02 09:27:38

问题


I have MyClass and I am doing a test-class for every method (Method1Test)

public class MyClass {
    public int method1(){
        int a = method2();
        return a;
    }
    public int method2(){
        return 0;
    }
}

@RunWith(MockitoJUnitRunner.class)
public class Method1Test {
    @InjectMocks
    private MyClass myClass = new MyClass();
    @Before
    public void setup(){}
    @Test
    public void test01(){
        Mockito.when(myClass.method2()).thenReturn(25);
        int a = myClass.method1();
        assertTrue("We did it!!!",a==25);
    }
}

The problem is that I am not able to mock the call to method2 to make it return a diferent value. The Mockito sentence don't do the work.

Very thanks ^_^


回答1:


You have to create a spy on the class-under-test and partially mock it by redefining the behavior for the method2() of the spy

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;


public class Method1Test {

  private MyClass myClass = new MyClass();

  @Test
  public void test01(){
    //given
    MyClass spy = spy(myClass); //create a spy for class-under-test
    when(spy.method2()).thenReturn(25); //partially override behavior of the spy
    //when
    int a = spy.method1(); //make the call to method1 of the _spy_!
    //then
    assertEquals(25, a);
  }
}

Apart from this, you don't require neither the Mockito Runner nor the @InjectMocks for your test as you're doing no injection of @Mock annotated mocks into the class-under-test.

Further, the message in the assertTrue statement is only displayed, when the condition of the assertion is NOT fulfilled. So it should be at least "We failed!!!" ;)




回答2:


In the end I find a transversal solution without create a new class (I haven't been able to do it because it is forbbiden in the actual project). I have overwrited the method in the test.

The solution is

public class MyClass {
    public int method1(){
        int a=0;
        a=method2();
        return a;
    }
    public int method2(){
        return 1;
    }
}

@RunWith(MockitoJUnitRunner.class)
public class Method1Test {
    @InjectMocks
    private MyClass myClass = new MyClass(){
        public int method2(){
            return 25;
        }
    };
    @Before
    public void setup(){}
    @Test
    public void test001(){
        Mockito.when(myClass.method2()).thenReturn(25);
        int a = myClass.method1();
        assertTrue("We did it!!!",a==25);
    }
}


来源:https://stackoverflow.com/questions/37095096/how-to-mock-a-call-of-an-inner-method-from-a-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!