我需要在Java类中模拟这样的方法:
public class Helper{
public static message(final String serviceUrl){
HttpClient httpclient = new HttpClient();
HttpMethod httpmethod = new HttpMethod();
// the below is the line that iam trying to mock
String code = httpClient.executeMethod(method);
}
}
我尝试用groovy编写junit,但由于grovy元编程技术不适用于Java类,因此无法这样做.在我的研究中,我发现JMockit是一个很好的框架,它还可以模拟使用新构造函数创建的对象.
有人可以告诉我如何用Java或groovy编写上述类的单元测试.
先进的谢谢
这是我到目前为止使用jmockit尝试过的测试用例,但是不起作用.
void testSend(){
def serviceUrl = properties.getProperty("PROP").toString()
new Expectations(){
{
HttpClient httpClient=new HttpClient();
httpClient.executeMethod(); returns null;
}
};
def responseXml = Helper.sendMessage(requestXml.toString(), serviceUrl)
}
解决方法:
使用jmockit,您还可以模拟实例创建.我喜欢稍微不同的技术:
@Test
public void testFoo(@Mocked final HttpClient client) {
new Expectations() {{
// expect instance creation and return mocked one
new HttpClient(... ); returns(client)
// expect invocations on this mocked instance
client.invokeSomeMethid(); returns(something)
}};
helper.message(serviceUrl)
}