java 使用 JMockit,如何模拟特定输入参数值的接口方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15200914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using JMockit, how do I mock an interface method for specific input parameter values?
提问by Marcin
Let's say I have an interface Foo
with method bar(String s)
. The only thing I want mocked is bar("test");
.
假设我有一个Foo
带有 method的接口bar(String s)
。我唯一想要嘲笑的是bar("test");
.
I cannot do it with static partial mocking, because I only want the bar
method mocked when "test" argument is being passed. I cannot do it with dynamic partial mocking, because this is an interface and I also do not want the implementation constructor mocked. I also cannot use interface mocking with MockUp
, because I have no ability to inject mocked instance, it is created somewhere in code.
我不能用静态部分模拟来做到这一点,因为我只希望在bar
传递“测试”参数时模拟该方法。我不能用动态部分模拟来做到这一点,因为这是一个接口,我也不希望实现构造函数被模拟。我也不能使用接口模拟MockUp
,因为我没有能力注入模拟实例,它是在代码中的某处创建的。
Is there something I am missing?
有什么我想念的吗?
采纳答案by Rogério
Indeed, for this situation you would need to dynamically mock the classes that implement the desired interface. But this combination (@Capturing
+ dynamic mocking) is not currently supported by JMockit.
实际上,对于这种情况,您需要动态模拟实现所需接口的类。但是@Capturing
JMockit 目前不支持这种组合(+ 动态模拟)。
That said, if the implementation class is known and accessible to test code, then it can be done with dynamic mocking alone, as the following example test shows:
也就是说,如果实现类是已知的并且可以被测试代码访问,那么它可以单独使用动态模拟来完成,如下面的示例测试所示:
public interface Foo {
int getValue();
String bar(String s);
}
static final class FooImpl implements Foo {
private final int value;
FooImpl(int value) { this.value = value; }
public int getValue() { return value; }
public String bar(String s) { return s; }
}
@Test
public void dynamicallyMockingAllInstancesOfAClass()
{
final Foo exampleOfFoo = new FooImpl(0);
new NonStrictExpectations(FooImpl.class) {{
exampleOfFoo.bar("test"); result = "aBcc";
}};
Foo newFoo = new FooImpl(123);
assertEquals(123, newFoo.getValue());
assertEquals("aBcc", newFoo.bar("test")); // mocked
assertEquals("real one", newFoo.bar("real one")); // not mocked
}
回答by Jun Jiang
final Foo foo = new MockUp<Foo>() {
@Mock
public bar(String s)(){
return "test";
}
}.getMockInstance();
foo.bar("") will now retun "test"...