How to override a method in unit tests that is called from which the class being tested

百般思念 提交于 2021-02-16 18:33:06

问题


I am testing a class A's function func1.

Func1 has a local variable of Class B and calls B's function func2. Code looks something like this:

public Class A
{
    public func1()
    {
       B object = new B();
       int x = object.func2(something);
    }
}

When I am testing func1 in its unit tests, I don't want func2 to get called.

So I am trying to do something like this in the test:

B textObject = new B()
{
   @override
   int func2(something)
   {
      return 5;
   }
}

But it is still calling the func2 in the class B. Please suggest how to handle this.


回答1:


If you want to override the new B() constructor call - place it in an own method.

public Class A
{

    public func1()
    {
       B object = newB();
       int x = object.func2(something);
    }

    protected B newB(){
        return new B();
    }
}

In your test you can then override the B constructor call.

public class APartitialMock extends A {

   protected B newB(){
      return new BMock();
   }
}

public class BMock extends B {

    int func2(something) {
        return 5
    }

}

Then use APartitialMock to test the func1 with your kind of B.

PS If you can or want to use a framework take a look at powermock - Mock Constructor




回答2:


I can make B as a class variable in A but that doesn't seem to help either. What would you suggest in this case?

If you make B as a class variable, then you can mock B, and "swap" it in the tested object of A.
Maybe not very elegant, but quick and simple.

An example:

public class B {
    int func2(int something){
        return 3*something;
    }
}

public class A
{
    // declare it as protected - a test need to have access to this field to replace it
    protected B object = new B();

    public int func1()
    {
       int x = object.func2(22);
       return x;
    }
}

And a test:

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class ATest {

    @Test
    public void test() {
        A myA = new A();
        B myB = mock(B.class);

        // dummy function
        when(myB.func2(anyInt())).thenReturn(20);

        // replace B with mocked B
        myA.object = myB;

        int actual = myA.func1();

        assertEquals(20, actual);
    }
}


来源:https://stackoverflow.com/questions/37235373/how-to-override-a-method-in-unit-tests-that-is-called-from-which-the-class-being

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