I used to rely on Mockito until today I have a final class with some static methods so I've to switched to JMockit. I knew nothing about it before so the question is: how can I apply the similar logic from Mockito to JMockit?

public final class ServiceData extends BaseData {

    private List<Data> data;

    public ServiceData(List<Data> data) {
         this.data = data;
         // something else
    }

    public static Container getContainer() {
         return super.getContainer();
    }

    public Data getDataAt(Index index) {
         return super.getContainer().get(index);
    }

}

The test written in Mockito looks like:

@Test
public void test() {
    ServiceData mockServiceData = mock(ServiceData.class);
    Data mockData = mock(Data.class);
    // only stubbing some of the methods
    Container mockContainer = spy(Container.class);
    doReturn(something).when(mockContainer.someMethod());
    when(mockServiceData.getContainer()).thenReturn(mockContainer);
    when(mockServiceData.getDataAt(any(Index.class)).thenReturn(mockData);

    // some assertions
}

This won't work since Mockito cannot mock final classes nor static methods (getContainer) So how can I write the same logic in JMockit? Thanks.

有帮助吗?

解决方案

The following is the JMockit equivalent for the example test:

@Test
public void test(
    @Mocked final ServiceData mockServiceData, @Mocked final Data mockData,
    @Mocked final Container mockContainer)
{
    // only stubbing some of the methods
    new Expectations(mockContainer) {{
        mockContainer.someMethod(); result = "something";
        mockServiceData.getContainer(); result = mockContainer;
        mockServiceData.getDataAt((Index) any); result = mockData;
    }};

    // some assertions
}

To mock static methods the syntax is the same, except that you would write ServiceData.getContainer(); result = mockContainer; instead.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top