Spock - Mock private field

只愿长相守 提交于 2021-02-11 15:06:41

问题


I have to mock private field:

public class A{
    private final B b;
    public A(){
        this.b = new B(new OtherService)
    }

    public test(){
        int i = b.test()
        if(i == 0)
           b.test1()
        else
           b.test2()
    }
}

and I have to create unit tests for methods in this kind of class and I have to mock class B is it even possible here?


回答1:


Please read my remarks here and here or in many other questions of this kind I answered concerning dependency injection (DI). The lack thereof in your tightly coupled application design is what stops you from testing and refactoring effectively.

So go refactor! Make sure your class has a constructor or setter by which to inject the dependency (here: the instance of B you wish to mock).

If your member was not final, you could use a Groovy-ism, just using the known private member name in the constructor like A a = new A(b: Mock(B)) according to my answer here, but this is an ugly alternative to driving good application design with automated tests and decouple your classes. If any class is difficult to test, in many cases (also here) it does not mean your testing skills or tools need to get better but your application design is flawed.



来源:https://stackoverflow.com/questions/64590395/spock-mock-private-field

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