Using spy to mock a full object created in the class which is tested

最后都变了- 提交于 2021-01-29 07:01:14

问题


I have the following structure:

class A {

    public A(String p){
        // ...
    }

    public String AMethod(String p){
        // ...
    }

}

class B {
    int method(String param){
        A a = new A(param); int n;
        String s = A.AMethod(param);
        // ... (initializes n, ...)
        return n;
    }
}

Now I want to test method in class B but control the output of AMethod when it is called. But since I do not create the object A in the test class of B, I cannot mock it normally - how can I mock object A instead?

I tried Mockito.spy but it doesn't seem to work:

this.ASpy = spy(new A());

when(ASpy.createSession(any())).then(invocation -> {
    // ... (*)
});

(*) still doen't get called... but spy should be the right solution, shouldn't it? My problem is: I never create an object A in my test class, only in method such an object is created but not in the test class.


回答1:


The best way to handle this (if possible) would be to modify the code of class B so that object A was injected into the method (passed as a parameter, set as a class field or instantiated with usage of a factory class - the factory would be injected as a field and the factory object could be mocked in the test to return a mocked object A).

If actual code modifications are not possible, you could use PowerMock's whenNew method and return a mocked object in your test.

A side note: if you're using JUnit 5, PowerMock may not be a viable solution - read more here.



来源:https://stackoverflow.com/questions/63426996/using-spy-to-mock-a-full-object-created-in-the-class-which-is-tested

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