why cannot we create spy for Parameterized Constructor using Mockito(为什么我们不能使用 Mockito 为参数化构造函数创建间谍)
问题描述
我的代码中只有参数化的构造函数,我需要通过它进行注入.
I have only parameterized constructor in my code and i need to inject through it.
我想监视参数化构造函数以注入模拟对象作为我的 junit 的依赖项.
I want to spy parameterized constructor to inject mock object as dependency for my junit.
public RegDao(){
//original object instantiation here
Notification ....
EntryService .....
}
public RegDao(Notification notification , EntryService entry) {
// initialize here
}
we have something like below :
RegDao dao = Mockito.spy(RegDao.class);
但是我们有什么东西可以让我在构造函数中注入模拟对象并监视它吗?
But do we have something that i can inject mocked object in the Constructor and spy it?.
推荐答案
您可以通过在 junit 中使用参数化构造函数实例化您的主类,然后从中创建一个间谍来做到这一点.
You can do that by instantiating your main class with parametrized constructor in your junit and then creating a spy from it.
假设您的主类是A
.其中 B
和 C
是它的依赖项
Let's suppose your main class is A
. Where B
and C
are its dependencies
public class A {
private B b;
private C c;
public A(B b,C c)
{
this.b=b;
this.c=c;
}
void method() {
System.out.println("A's method called");
b.method();
c.method();
System.out.println(method2());
}
protected int method2() {
return 10;
}
}
然后您可以使用下面的参数化类为此编写 junit
Then you can write junit for this using your parametrized class as below
@RunWith(MockitoJUnitRunner.class)
public class ATest {
A a;
@Mock
B b;
@Mock
C c;
@Test
public void test() {
a=new A(b, c);
A spyA=Mockito.spy(a);
doReturn(20).when(spyA).method2();
spyA.method();
}
}
测试类的输出
A's method called
20
- 这里
B
和C
是您使用参数化构造函数注入到您的类A
中的模拟对象. - 然后我们创建了一个名为
spyA
的A
的spy
. - 我们通过修改类
A
中受保护方法method2
的返回值来检查spy
是否真的有效,这不可能如果spyA
不是A
的实际spy
.
- Here
B
andC
are mocked object that you injected in your classA
using parametrized constructor. - Then we created a
spy
ofA
calledspyA
. - We checked if
spy
is really working by modifying the return value of a protected methodmethod2
in classA
which could not have been possible ifspyA
was not an actualspy
ofA
.
这篇关于为什么我们不能使用 Mockito 为参数化构造函数创建间谍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我们不能使用 Mockito 为参数化构造函数创建间谍


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01