Mockito:如何验证在方法中创建的对象上调用了方法? [英] Mockito : how to verify method was called on an object created within a method?
问题描述
我是 Mockito 的新手.
给定下面的类,我如何使用 Mockito 来验证 someMethod
在 foo
被调用后被调用了一次?
公共类Foo{公共无效 foo(){Bar bar = new Bar();bar.someMethod();}}
我想拨打以下验证电话,
verify(bar, times(1)).someMethod();
其中 bar
是 Bar
的模拟实例.
依赖注入>
如果您注入 Bar 实例或用于创建 Bar 实例的工厂(或执行此操作的其他 483 种方法之一),您将拥有执行测试所需的访问权限.
工厂示例:
给定一个像这样写的 Foo 类:
公共类 Foo {私人 BarFactory barFactory;公共 Foo(BarFactory 工厂){this.barFactory = 工厂;}公共无效 foo() {Bar bar = this.barFactory.createBar();bar.someMethod();}}
在您的测试方法中,您可以像这样注入 BarFactory:
@Test公共无效 testDoFoo() {Bar bar = mock(Bar.class);BarFactory myFactory = new BarFactory() {公共栏 createBar() { 返回栏;}};Foo foo = new Foo(myFactory);foo.foo();验证(酒吧,时间(1)).someMethod();}
奖励:这是 TDD 如何推动代码设计的一个示例.
I am new to Mockito.
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();
where bar
is a mocked instance of Bar
.
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.
Factory Example:
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();
}
}
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();
}
Bonus: This is an example of how TDD can drive the design of your code.
这篇关于Mockito:如何验证在方法中创建的对象上调用了方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!