使用Mockito mock final方法和final类
2022-07-23 本文已影响0人
ShootHzj
代码已经上传到gitee
准备
书写MyList类
package com.github.shoothzj.mockito;
import java.util.AbstractList;
public class MyList extends AbstractList<String> {
@Override
public String get(final int index) {
return null;
}
@Override
public int size() {
return 0;
}
final public int finalMethod() {
return 0;
}
}
书写FinalList,我们接下来书写一个Final类,继承MyList
public final class FinalList extends MyList {
@Override
public int size() {
return 1;
}
}
配置Mockito支持Final方法和Final类
在src/test/resources/mockito-extensions
中添加名为org.mockito.plugins.MockMaker
的文件,内容为
mock-maker-inline
mock final方法
package com.github.shoothzj.mockito;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class MyListTest {
@Test
public void testMockFinalMethod() {
MyList myList = new MyList();
MyList mock = Mockito.mock(MyList.class);
Mockito.when(mock.finalMethod()).thenReturn(1);
Assertions.assertNotEquals(mock.finalMethod(), myList.finalMethod());
}
}
mock final类
package com.github.shoothzj.mockito;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class FinalListTest {
@Test
public void testMockFinalClass() {
FinalList finalList = new FinalList();
FinalList mock = Mockito.mock(FinalList.class);
Mockito.when(mock.size()).thenReturn(2);
Assertions.assertNotEquals(mock.size(), finalList.size());
}
}