How can I mock methods of @InjectMocks class?(如何模拟 @InjectMocks 类的方法?)
问题描述
例如我有处理程序:
@Component
public class MyHandler {
@AutoWired
private MyDependency myDependency;
public int someMethod() {
...
return anotherMethod();
}
public int anotherMethod() {...}
}
为了测试它,我想写这样的东西:
to testing it I want to write something like this:
@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {
@InjectMocks
private MyHandler myHandler;
@Mock
private MyDependency myDependency;
@Test
public void testSomeMethod() {
when(myHandler.anotherMethod()).thenReturn(1);
assertEquals(myHandler.someMethod() == 1);
}
}
但每当我尝试模拟它时,它实际上都会调用 anotherMethod()
.我应该用 myHandler
做什么来模拟它的方法?
But it actually calls anotherMethod()
whenever I try to mock it. What should I do with myHandler
to mock its methods?
推荐答案
首先mock MyHandler方法的原因可能如下:我们已经测试过anotherMethod()
,它的逻辑很复杂,那么,如果我们可以verify
它正在调用,为什么我们需要再次测试它(就像 someMethod()
的一部分)?
我们可以通过:
First of all the reason for mocking MyHandler methods can be the following: we already test anotherMethod()
and it has complex logic, so why do we need to test it again (like a part of someMethod()
) if we can just verify
that it's calling?
We can do it through:
@RunWith(MockitoJUnitRunner.class)
class MyHandlerTest {
@Spy
@InjectMocks
private MyHandler myHandler;
@Mock
private MyDependency myDependency;
@Test
public void testSomeMethod() {
doReturn(1).when(myHandler).anotherMethod();
assertEquals(myHandler.someMethod() == 1);
verify(myHandler, times(1)).anotherMethod();
}
}
注意:在 'spying' 对象的情况下,我们需要使用 doReturn
而不是 thenReturn
(小解释是 这里)
Note: in case of 'spying' object we need to use doReturn
instead of thenReturn
(little explanation is here)
这篇关于如何模拟 @InjectMocks 类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何模拟 @InjectMocks 类的方法?


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01