Monday, July 25, 2011

JMockit and static methods

Static methods are painful in Java when mocking but JMockit makes some impossible testing possible, though not easy:

public final class MockitEg {
    public static final int SHOE_SIZE = 13;

    public static int shoeSize() {
        System.out.println("MockitEg.shoeSize");
        return SHOE_SIZE;
    }

    private MockitEg() {
    }
}

public class MockitTest {
    private static final int MOCK_SHOE_SIZE = SHOE_SIZE + 29;

    @Test
    public void shouldMockStaticMethod() {
        new NonStrictExpectations() {
            final MockitEg mock = null;

            {
                MockitEg.shoeSize();
                result = new MockitEgDelegate();
            }
        };

        assertThat(MockitEg.shoeSize(),
                is(equalTo(MOCK_SHOE_SIZE)));
    }

    private static final class MockitEgDelegate
            implements Delegate {
        public static int shoeSize() {
            return MOCK_SHOE_SIZE;
        }
    }
}

The test passes.

No comments: