从Mockito切换到JMockit



我曾经依赖Mockito,直到今天我有一个带有一些静态方法的最终类,所以我不得不切换到JMockit。我以前对此一无所知,所以问题是:如何将 Mockito 中的类似逻辑应用于 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);
    }
}

用Mockito编写的测试看起来像:

@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
}

这是行不通的,因为Mockito不能模拟最终类或静态方法(getContainer)那么如何在JMockit中编写相同的逻辑呢?谢谢。

以下是示例测试的JMockit等效项:

@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
}

要模拟static方法,语法是相同的,只是您将编写ServiceData.getContainer(); result = mockContainer;

相关内容

  • 没有找到相关文章

最新更新