gpt4 book ai didi

java - Mockito:一个类的所有实例的模拟实例方法

转载 作者:搜寻专家 更新时间:2023-10-30 21:11:24 26 4
gpt4 key购买 nike

我试图 stub 一个特定类的实例方法,这样当这个 Foo 类的任何实例调用这个实例方法 doSomething 时,相同的 object 被返回(见下面的代码)。但是,mockito 不允许在验证或 stub 之外使用任何匹配器。

Bar object = new Bar();
given(any(Foo.class).doSomething(Arg.class)).willReturn(object);

Foo.class 中:

Bar doSomething(Arg param) {
Bar bar = new Bar();
// Do something with bar
return bar;
}

我可以用 Mockito 实现这个目标吗?谢谢!

最佳答案

如果您希望 Foo 在您调用 doSomething 时返回相同的 Bar 实例,您应该使用 PowerMock Foo 的任何实例上的方法。这是一个例子:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class FooMockAllInstanceTest {

@Test
public void testMockInstanceofObjectCreation() throws Exception {
Bar mockBar = PowerMockito.mock(Bar.class);
when(mockBar.sayHello()).thenReturn("Hi John!");
PowerMockito.whenNew(Bar.class)
.withNoArguments()
.thenReturn(mockBar);

Foo myFooOne = new Foo();
assertEquals(mockBar, myFooOne.doSomething("Jane"));

Foo myFooTwo = new Foo();
assertEquals(mockBar, myFooTwo.doSomething("Sarah"));

Baz bazOne = new Baz();
assertEquals(mockBar, bazOne.doSomething("Sam"));

Baz bazTwo = new Baz();
assertEquals(mockBar, bazTwo.doSomething("Nina"));
}
}

即使在调用 Baz 时,此示例也会返回相同的 Bar 对象。这是 Baz 类,

public class Baz {

public Bar doSomething(String name) {
Foo foo = new Foo();
return foo.doSomething(name);
}
}

更新 2

还有另一种使用 PowerMock 进行测试的稍微好一点的方法。在这里,

@Test
public void testStubbingMethod() throws Exception {
Bar mockBar = PowerMockito.mock(Bar.class);
when(mockBar.sayHello()).thenReturn("Hi John!");

PowerMockito.stub(PowerMockito.method(Foo.class, "doSomething",
String.class)).toReturn(mockBar);

Foo myFooOne = new Foo();
assertEquals(mockBar, myFooOne.doSomething("Jane"));

Foo myFooTwo = new Foo();
assertEquals(mockBar, myFooTwo.doSomething("Sarah"));

Baz bazOne = new Baz();
assertEquals(mockBar, bazOne.doSomething("Sam"));

Baz bazTwo = new Baz();
assertEquals(mockBar, bazTwo.doSomething("Nina"));
}

关于java - Mockito:一个类的所有实例的模拟实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46185469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com