Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Using JMockit

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)            
}
like image 550
Npa Avatar asked Dec 06 '25 02:12

Npa


1 Answers

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)
}
like image 171
Konstantin Pribluda Avatar answered Dec 08 '25 16:12

Konstantin Pribluda