I need to mock a method in a java class that is like this:
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);
}
}
I have tried to write the junit in groovy, but not able to do so as grrovy meta-proggraming techniques do not apply for java classes. On my research, i have found out that JMockit is a good framework that can also mock objects that are created using new constructor.
Can somebody show me how to write the unittest for the above class either in java or in groovy.
Advanced Thanks
this is the test case that i have tried so far using jmockit, but does not work..
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)
}
With jmockit you can also mock instance creation. I prefer slightly different technique:
@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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With