使用 spy 模拟在测试的类中创建的完整对象

编程入门 行业动态 更新时间:2024-10-22 07:28:52
本文介绍了使用 spy 模拟在测试的类中创建的完整对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下结构:

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 模拟在测试的类中创建的完整对象

本文发布于:2023-10-31 04:50:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类中   对象   完整   测试   spy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!