该系列文章翻译自https://www.baeldung.com/mockito-series
我们为MyList类增加了一个final方法,并且扩展了一个final类,如下:
public class MyList extends AbstractList {
final public int finalMethod() {
return 0;
}
}
public final class FinalList extends MyList {
@Override
public int size() {
return 1;
}
}
1. 配置
为了让Mockito能够模拟final类和方法,需要做额外的配置。我们需要在项目的src/test/resources/mockito-extensions 目录下添加文件org.mockito.plugins.MockMaker,并在文件中添加一行
mock-maker-inline
image.png
2. 模拟final方法
@Test
public void whenMockFinalMethodMockWorks() {
MyList myList = new MyList();
MyList mock = mock(MyList.class);
when(mock.finalMethod()).thenReturn(1);
assertNotEquals(mock.finalMethod(), myList.finalMethod());
}
3. 模拟final类
@Test
public void whenMockFinalClassMockWorks() {
FinalList finalList = new FinalList();
FinalList mock = mock(FinalList.class);
when(mock.size()).thenReturn(2);
assertNotEquals(mock.size(), finalList.size());
}
网友评论