java - 使用 Autowired 类测试 void 方法
问题描述
我是 Spring 的初学者,如果它调用方法,我需要为这个类编写测试:
class ClassOne {
@Autowired
AutowiredClass a1;
@Autowired
AutowiredClass a2;
void methodOne() {
a1.method1();
}
void methodTwo() {
a2.method2();
}
}
我试过写测试,但失败了,得到了 NPE:
class ClassOneTest {
@Autowired
ClassOneInterface c1i;
@Test
public void testMethod1() {
c1i.methodOne(); // <- NPE appears here..
Mockito.verify(ClassOne.class, Mockito.times(1));
}
}
成功测试 void 方法会很棒。
解决方案
您可以使用单元测试来验证:
@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest {
@InjectMocks
private ClassOne c1 = new ClassOne();
@Mock
private AutowiredClass a1;
@Mock
private AutowiredClass a2;
@Test
public void methodOne() {
c1.methodOne(); // call the not mocked method
Mockito.verify(a1).method1(); //verify if the a1.method() is called inside the methodOne
}
}
推荐阅读
- amazon-ec2 - 客户端无法连接到 Hazelcast-jet ec2 集群
- python - 删除pytorch中张量字典列表中所有张量的某些元素
- android - 偏好屏幕为白色
- python - 如何在 Python 中更改元组?(如果可能的话)
- java - java如何处理键盘上“enter”键的输入
- r - 基于R中的逻辑操作删除重复行
- android - setContentView() 首先或最后调用?
- angular - 从 Observable 获取字符串响应
- python - Python matplotlib.animation.FuncAnimation 永远不会进行第二帧迭代
- python-3.x - 矩形是否重叠、不重叠或相同?