gpt4 book ai didi

java - 从 Mockito 切换到 JMockit

转载 作者:搜寻专家 更新时间:2023-11-01 02:47:12 24 4
gpt4 key购买 nike

我以前一直依赖 Mockito,直到今天我有一个带有一些静态方法的期末类(class),所以我不得不切换到 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; 代替。

关于java - 从 Mockito 切换到 JMockit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com