我有以下结构:
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; } }现在我想在 B 类中测试 method 但在调用时控制 AMethod 的输出.但是由于我没有在B的测试类中创建对象A,所以无法正常mock它——我该如何mock对象A呢?
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?
我试过 Mockito.spy 但它似乎不起作用:
this.ASpy = spy(new A()); when(ASpy.createSession(any())).then(invocation -> { // ... (*) });(*) 仍然没有被调用...但是 spy 应该是正确的解决方案,不是吗?我的问题是:我从来没有在我的测试类中创建对象 A,只有在 method 中创建了这样的对象,但不在测试类中.
(*) 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.
推荐答案处理这个问题的最好方法(如果可能的话)是修改类 B 的代码,以便将对象 A 注入到方法中(作为参数传递),设置为类字段或使用工厂类实例化 - 工厂将作为字段注入,工厂对象可以在测试中模拟以返回模拟对象 A).
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).
如果实际的代码修改是不可能的,你可以使用 PowerMock 的 whenNew 方法 并在您的测试中返回一个模拟对象.
If actual code modifications are not possible, you could use PowerMock's whenNew method and return a mocked object in your test.
附注:如果您使用的是 JUnit 5,PowerMock 可能不是一个可行的解决方案 - 阅读更多 此处.
A side note: if you're using JUnit 5, PowerMock may not be a viable solution - read more here.
更多推荐
使用 spy 模拟在测试的类中创建的完整对象
发布评论