在没有PowerMock的情况下模拟类中的对象

时间:2019-05-08 18:19:55

标签: junit mocking mockito

我想使用Powermock模拟类内的对象。我该怎么办?

我尝试使用间谍,但没有用。

/** SOURCE CODE **/
abstract class Parent {
    protected final Caller caller = new Caller();
    public abstract void call(Connection, Integer);
}

class Child1 extends Parent {

    @Override
    public void call(Connection con, Integer id1) {
        // some logic
        caller.getSomething1(connection, id1);
    }
}

class Child2 extends Parent {

    @Override
    public void call(Connection con, Integer id2) {
        // some logic
        caller.getSomething2(connection, id2);
    }
}

class Activity {

     @Inject
     private MyConnection connection;

     public Response process(Request r) {
           Parent p = ChildFactory.getChild(r); // returns a child based on some logic related to p
           p.call(connection, r.getId());
           return new Response("SUCCESS");
     }
}

/** TEST CODE **/

public class Test {

    @InjectMocks
    private Activity activity;

    @Mock
    private Connection connectionMock;

    private Caller caller;

    @Before
    public void setup() throws Exception {
         caller = Mockito.spy(Caller.class);
Mockito.doReturn(null).when(caller).getSomething1(Mockito.any(), Mockito.any());
Mockito.doReturn(null).when(caller).getSomething2(Mockito.any(), Mockito.any());
    }

    @Test
    public void testProcess() {
        Request r = new Request(1);
        Response r = activity.process(r);
        Assert.assertEquals(r.getResult(), "SUCCESS"); 
    }
}

我想模拟在Parent类中创建的调用者对象。每个孩子都会食用它。我不担心调用的结果,因此我想在不使用PowerMock的情况下模拟调用者的所有调用(即getSomething1,getSomething2)。

我尝试使用间谍,但未使用间谍对象,而是在调用getSomething1和getSomething2方法。

1 个答案:

答案 0 :(得分:0)

您可以使用ReflectionTestUtils#setField

@Before
public void setup() throws Exception {
     caller = Mockito.spy(Caller.class);
     Mockito.doReturn(null).when(caller).getSomething1(Mockito.any(), Mockito.any());
     Mockito.doReturn(null).when(caller).getSomething2(Mockito.any(), Mockito.any());

     // ... obtain children here ...

     ReflectionTestUtils.setField(child1, "caller", caller);
     ReflectionTestUtils.setField(child2, "caller", caller);
}

或者更好的是,您不实例化Caller类中的Child实例,而是通过例如构造函数进行注入