Mockito:如何在方法中创建的对象上调用方法? [英] Mockito : how to verify method was called on an object created within a method?
问题描述
我是Mockito的新手。
I am new to Mockito.
鉴于下面的课程,如何使用Mockito验证 someMethod
在调用 foo
之后调用了一次?
Given the class below, how can I use Mockito to verify that someMethod
was invoked exactly once after foo
was invoked?
public class Foo
{
public void foo(){
Bar bar = new Bar();
bar.someMethod();
}
}
我想进行以下验证电话,
I would like to make the following verification call,
verify(bar, times(1)).someMethod();
其中 bar
是<的模拟实例code> Bar 。
推荐答案
如果您注入Bar实例或用于创建的工厂Bar实例(或其他483种方法之一),您可以进行必要的访问以执行测试。
If you inject the Bar instance, or a factory that is used for creating the Bar instance (or one of the other 483 ways of doing this), you'd have the access necessary to do perform the test.
工厂示例:
给定一个这样写的Foo类:
Given a Foo class written like this:
public class Foo {
private BarFactory barFactory;
public Foo(BarFactory factory) {
this.barFactory = factory;
}
public void foo() {
Bar bar = this.barFactory.createBar();
bar.someMethod();
}
}
在您的测试方法中,您可以注入这样的BarFactory :
in your test method you can inject a BarFactory like this:
@Test
public void testDoFoo() {
Bar bar = mock(Bar.class);
BarFactory myFactory = new BarFactory() {
public Bar createBar() { return bar;}
};
Foo foo = new Foo(myFactory);
foo.foo();
verify(bar, times(1)).someMethod();
}
奖励:这是TDD如何推动代码设计的示例。
Bonus: This is an example of how TDD can drive the design of your code.
这篇关于Mockito:如何在方法中创建的对象上调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!