Using Mockito to mock a class method inside another class(使用 Mockito 在另一个类中模拟一个类方法)
问题描述
我正在尝试使用 Mockito/JUnit 为这样的函数编写单元测试:
I'm trying to write unit tests with Mockito / JUnit for a function like this:
class1 {
method {
object1 = class2.method // method that I want to fake the return value
// some code that I still want to run
}
}
在 Mockito 中有什么方法可以存根 class2.method 的结果吗?我正在尝试提高 class1 的代码覆盖率,因此我需要调用它的实际生产方法.
Is there any way in Mockito to stub the result of class2.method? I'm trying to improve code coverage for class1 so I need to call its real production methods.
我查看了 Mockito API 的 spy 方法,但这会覆盖整个方法,而不是我想要的部分.
I looked into the Mockito API at its spy method but that would overwrite the whole method and not the part that I want.
推荐答案
我想我理解你的问题.让我重新表述一下,您有一个正在尝试测试的函数,并且想要模拟在该函数中调用的函数的结果,但在不同的类中.我已经通过以下方式处理了.
I think I am understanding your question. Let me re-phrase, you have a function that you are trying to test and want to mock the results of a function called within that function, but in a different class. I have handled that in the following way.
public MyUnitTest {
private static final MyClass2 class2 = mock(MyClass2.class);
@Begin
public void setupTests() {
when(class2.get(1000)).thenReturn(new User(1000, "John"));
when(class2.validateObject(anyObj()).thenReturn(true);
}
@Test
public void testFunctionCall() {
String out = myClass.functionCall();
assertThat(out).isEqualTo("Output");
}
}
这样做是在使用 @Before 注释包装的函数中,我正在设置我希望 class2 中的函数如何响应给定的特定输入.然后,在实际测试中,我只是在我想要测试的类中调用我试图测试的函数.在这种情况下,myClass.functionCall() 正常运行,您不会覆盖它的任何方法,而只是模拟它从 MyClass2 中的方法(或方法)获得的输出.
What this is doing is that within the function wrapped with the @Before annotation, I am setting up how I want the functions in class2 to respond given specific inputs. Then, from within the actual test, I am just calling the function that I am trying to test in the class I want to test. In this case, the myClass.functionCall() is running through as normal and you are not overwriting any of its methods, but you are just mocking the outputs that it gets from the methods (or method) within MyClass2.
这篇关于使用 Mockito 在另一个类中模拟一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Mockito 在另一个类中模拟一个类方法


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01