简体   繁体   中英

How do I mock static chained methods using jmockit in Java

InetAddress.getLocalHost().getHostName()

如何利用JMockit来测试上面的代码?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM