java jMock 模拟类和接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/968171/
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
jMock Mocking Classes and Interface
提问by Roy Marco Aruta
I was experimenting jMock as my mocking framework for my project. I came into a situation where I need to mock both a class and an interface. I used the ClassImposteriser.INSTANCEto initiate the impostor of the context.
我正在试验 jMock 作为我项目的模拟框架。我遇到了一种情况,我需要同时模拟一个类和一个接口。我使用ClassImposteriser.INSTANCE来启动上下文的冒名顶替者。
Supposing a class Validatorand an interface Personto mock. When I was going to mock the Interface Person, I ran to a problem NoClassFoundDefError. When I mocked the class Validator, there was no problem.
假设一个类Validator和一个接口Person来模拟。当我准备模拟接口时Person,我遇到了一个问题NoClassFoundDefError。当我嘲笑班级时Validator,没有问题。
I need both that class and interface but I can't solve the problem. Please HELP.
我需要那个类和接口,但我无法解决问题。请帮忙。
Code Example:
代码示例:
Mockery
嘲弄
private Mockery context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.Class) }};
private Mockery context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.Class) }};
Class :
班级 :
private Validator validator;
private Validator validator;
Interface :
界面 :
private Person person;
private Person person;
Inside Test Method
内部测试方法
validator = context.Mock(Validator.class);----> Working
person = context.Mock(Person.class);---->NoClassFoundDefError
validator = context.Mock(Validator.class);----> 工作
person = context.Mock(Person.class);---->NoClassFoundDefError
回答by bm212
The code as you present it won't compile (it should be ClassImposteriser.INSTANCE). The example code below seems to work fine. Perhaps you could provide some more details?
您提供的代码将无法编译(它应该是 ClassImposteriser.INSTANCE)。下面的示例代码似乎工作正常。也许您可以提供更多详细信息?
public class Example {
private Mockery context = new JUnit4Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
@Test
public void testStuff() {
Validator validator = context.mock(Validator.class);
Person person = context.mock(Person.class);
// do some stuff...
}
public static interface Person {
}
public static class Validator {
}
}

