Skip to content

Mocking static methods not working when initializing HttpServlet with @Tested #255

@Spookyguy

Description

@Spookyguy

In the following code, InetAddress does not get mocked. The call of InetAddress#getByName in class Servlet.java runs the method of the real class (which fails, because of 'managementHost' is not found).

I suppose that the mock is not set up before Servlet#init is called by the routine which is used to initialize objects annotated with @tested.

With JMockit 1.19 all works well and I learned that Release 1.19 did not call Servlet#init while initializing the object servlet, but since 1.20 it does.

`
public class MockTest {

@Tested
private Servlet servlet;

@Mocked
private InetAddress inetAddress;

@Before
public void recordConfig() throws UnknownHostException {

    new NonStrictExpectations() {
        {
            InetAddress.getByName(anyString);
            result = inetAddress;
        }
    };

}

@Test
public void mockTest() throws Exception {

    //        classInTheMiddle.init(servletConfig);

}

}
`

`public class Servlet extends HttpServlet {

@Override
public synchronized void init(ServletConfig conf) throws ServletException {
    try {
        final InetAddress inetAddress = InetAddress.getByName("managementHost");
    } catch (final UnknownHostException e) {
        throw new ServletException(e.getMessage(), e);
    }
}

}`

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions