java - JMockit - 如何注入抽象方法
问题描述
我正在尝试为扩展抽象类的类编写单元测试,但测试仍在尝试调用真正的抽象方法。有没有办法注入一个模拟抽象类并验证抽象方法是否被调用?
测试
public class TestThisClassTest {
@Tested
TestThisClass testThisClass;
@Injectable
String names;
@Injectable
String username;
@Injectable
char[] password = {'t', 'e', 's', 't', 's'};;
@Injectable
String destinationName;
@Injectable
AbstractClass abstractClass; // Thought this would inject but it's not
@Test(description = "Verify that sendMessageAbstractMethod is called")
public void testSendMessage(@Mocked ObjectMessage message) throws Exception {
testThisClass.sendMessage(message); // This is instantiating AbstractClass when it shouldn't be
new Verifications(){{
abstractClass.sendMessageAbstractMethod((Object) any);
times = 1;
}};
}
}
TestThisClass.class
public class TestThisClass extends AbstractClass {
public TestThisClass() {
super();
}
@Inject
public TestThisClass(String names, String username, char[] password, String destinationName) {
super(names, username, password, destinationName);
}
public void sendMessage(Object message) throws Exception { // Trying to test this method
sendMessageAbstractMethod(message); // This is "doing stuff." Need it verify this is called and move on
}
}
抽象类
public abstract class AbstractClass {
public AbstractClass(String names, String username, char[] password, String destinationName) {
this.names = names;
this.username = username;
this.password = password;
this.destinationName = destinationName;
}
protected void sendMessageAbstractMethod(Object message) throws Exception {
//do stuff
}
}
解决方案
public class TestThisClassTest {
@Injectable
String names;
@Injectable
String username;
@Injectable
char[] password = {'t', 'e', 's', 't', 's'};;
@Injectable
String destinationName;
@Test
public void testSendMessage(@Mocked ObjectMessage message) throws Exception {
TestThisClass abstractImpl = spy(new TestThisClass());
doNothing().when(abstractImpl).sendMessageAbstractMethod(any());
abstractImpl.sendMessage(message));
new Verifications(){{
verify(abstractImpl, times(1)).sendMessage(any());
}};
}
}
推荐阅读
- python-3.x - 通过 Glob 获取所有虚拟机的路径
- php - 在htaccess中动态获取域名
- python - 在范围内调用 asyncio Future
- ruby-on-rails - Rails 5.2 升级导致 ErrorController 失败并显示通用错误页面
- jquery - HTML2Canvas 不工作,需要控制台图像 url
- python - 如果工作表不存在,熊猫将工作表附加到工作簿,否则覆盖工作表
- node.js - 当我在猫鼬中删除包含嵌套子文档的文档时,如何自动删除嵌套子文档?
- mysql - 无法解决 eclipse 的类型问题
- laravel - 在 Laravel 中,如何验证选择选项乘法类型数组(名称 [])?
- hybris - 使用 Hybris hotfolder 时预处理 csv 文件以将键值转换为小写