surya
surya

Reputation: 189

How do I mock static chained methods using jmockit in Java

InetAddress.getLocalHost().getHostName()

How do I leverage JMockit in order to test the above code?

Upvotes: 1

Views: 2427

Answers (2)

Konstantin Pelepelin
Konstantin Pelepelin

Reputation: 1563

It should be enough to declare @Mocked InetAddress var1. By default, all methods of a @Mocked type, including static methods, return mocks. Then, the only calls to be stubbed ("recorded") in the Expectations are those with results important for the code being tested or those to be verified.

Upvotes: 1

Thunderforge
Thunderforge

Reputation: 20575

The chained method you gave is equivalent to the following:

InetAddress localHost = InetAddress.getLocalhost();
String hostName = localHost.getHostName();

Therefore, we need to break this into two mocks.

The second part is easily done by just mocking an InetAddress and putting it in an Expectations block like so:

@Test
public void myTest(@Mocked InetAddress mockedLocalHost) throws Exception {

    new Expectations() {{
       mockedLocalHost.getHostName();
       result = "mockedHostName";
    }};

    // More to the test
}

But how do we get mockedLocalHost to be the instance that is returned when we call InetAddress.getLocalhost()? With partial mocking, which can be used for any static methods. The syntax for that is to include the class containing the static method as a parameter for new Expecations() and then mock it as we would any other method call:

@Test
public void myTest(@Mocked InetAddress mockedLocalHost) throws Exception {

    new Expectations(InetAddress.class) {{
       InetAddress.getLocalHost();
       result = mockedLocalHost;

       mockedLocalHost.getHostName();
       result = "mockedHostName";
    }};

    // More to the test
}

This will result in mocking InetAddress.getLocalHost().getHostName() as you planned.

Upvotes: 2

Related Questions