【发布时间】:2013-08-12 20:10:34
【问题描述】:
看起来 EasyMock 3.2 版现在支持使用注释来设置模拟对象。我是 EasyMock(和一般 Java)的新手,我正在尝试了解如何使用它。这些注释是做一些新的事情还是只是提供另一种做事的方式? documentation 说:
从 EasyMock 3.2 开始,现在可以使用注释创建模拟。这是一个不错的 和更短的方法来创建你的模拟并将它们注入测试类。 这是上面的示例,现在使用注释:...
然后有一个清单显示了@TestSubject 和@Mock 注释的使用,但我不明白它是如何工作的。似乎它神奇地将被测类的私有字段设置为模拟对象。在我的大多数情况下,我只想制作返回预定义值的模拟对象,以便在 JUnit 测试用例中使用(目前不关心验证调用了哪些对象、调用了多少次等)。例如,对于某些测试,我想创建一个像这样的假 HttpServletRequest 对象:
public class SomeTest {
// Construct mock object for typical HTTP request for the URL below
private static final String REQUEST_URL = "http://www.example.com/path/to/file?query=1&b=2#some-fragment";
private static final Map<String, String> requestHeaderMap;
static {
Map<String, String> requestHeaders = new LinkedHashMap<String, String>();
requestHeaders.put("host", "www.example.com");
// ... (add any other desired headers here) ...
requestHeaderMap = Collections.unmodifiableMap(requestHeaders);
}
private HttpServletRequest httpServletRequest;
// ...
@Before
public void setUp() throws Exception {
httpServletRequest = createNiceMock(HttpServletRequest.class);
expect(httpServletRequest.getRequestURI()).andReturn(REQUEST_URL).anyTimes();
expect(httpServletRequest.getHeaderNames()).andReturn(Collections.enumeration(requestHeaderMap.keySet())).anyTimes();
capturedString = new Capture<String>();
expect(httpServletRequest.getHeader(capture(capturedString))).andAnswer(new IAnswer<String>() {
public String answer() throws Throwable {
String headerName = capturedString.getValue().toLowerCase();
if (requestHeaderMap.containsKey(headerName))
return requestHeaderMap.get(headerName);
else
return "";
}
}).anyTimes();
replay(httpServletRequest);
// ...
}
@Test
public void someMethod_givenAnHttpServletRequest_shouldDoSomething() {
// ...
}
}
我可以更改上面的代码以使用注释吗?如果是这样,我应该吗?什么情况下?
我认为也许将 @Mock 注释放在实例变量声明之上会自动处理 createNiceMock(...) 部分,但这似乎不起作用,所以我怀疑我误解了什么。
【问题讨论】:
-
已经使用过 EasyMock 和 Mockito,如果你还没有花很多时间在 EasyMock 上,你可能想看看 Mockito。我发现它更容易使用。
-
@AlperAkture,是的,我听说过 Mockito,可能会检查一下以备将来使用,但在这种情况下,我必须使用 EasyMock。