简体   繁体   English

如何使用参数化构造函数模拟类的对象?

[英]How do I mock an object of a class with parameterized constructor?

For the code 对于代码

public class A{
    public A (B b, C c){
    //do something here
    }
}

For testing, I wanted to create a mock object. 为了进行测试,我想创建一个模拟对象。 What I am doing now is 我现在正在做的是

B bmock = mock(B);
C cmock = mock(C);
A aobject = new A(bmock, cmock);

However, this doesn't allow me call verify() on aobject as it is not mocked. 但是,这不允许我在对象上调用verify(),因为它没有被模拟。 How to do that? 怎么做?

You could use a Spy : 您可以使用Spy

A aobject = spy(new A(bmock, cmock));

So you are actually calling the implementation of A but can still verify interactions. 因此,您实际上是在调用A的实现,但仍可以验证交互。

See the doc for details: http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#spy(T) 有关详细信息,请参见文档: http : //site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#spy(T)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何仅使用参数化构造函数为类创建对象? - how to create object for a class with only parameterized constructor? 如何检索参数化类的类 - How do I retrieve the Class for a Parameterized Class 如何使用采用 Class 的构造函数模拟 object? - How to mock object with constructor that takes a Class? 如何从另一个类中的public类型的参数化构造函数中调用默认类型的参数化构造函数? - How can I call parameterized constructor of default type from a parameterized constructor of type public which is in another class? 我如何通过将对象作为参数传递来实例化CDI bean,就像我从参数化构造函数中以普通Java实例化新对象一样? - How do I instantiate a CDI bean by passing an object as parameter just like I instantiate a new object in plain Java from a parameterized constructor? Redisson中仅具有参数化构造函数的类的对象反序列化 - Object deserializtion in Redisson for a class with only parameterized constructor 如何在参数化构造函数中指定多个枚举? - How do I specify the multiple enums in the parameterized constructor? 如何使用带有可变参数构造函数的 JUnit 参数化运行器? - How do I use a JUnit Parameterized runner with a varargs constructor? 如何使用默认访问修饰符创建构造函数是参数化构造函数的类的对象 - How to create the object of class where constructor is parameterized constructor using default access modifier 如何在没有(非默认)构造函数的Java类中模拟对象? - How do I mock objects in a Java class that has no (non-default) constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM