使用Mockito测试抽象类 [英] Using Mockito to test abstract classes

查看:1075
本文介绍了使用Mockito测试抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个抽象类。当然,我可以手动编写一个继承自该类的模拟

I'd like to test an abstract class. Sure, I can manually write a mock that inherits from the class.

我可以使用模拟框架(我使用的是Mockito)而不是手工制作我的模拟吗?如何?

Can I do this using a mocking framework (I'm using Mockito) instead of hand-crafting my mock? How?

推荐答案

以下建议让您在不创建真实子类的情况下测试抽象类 - 模拟子类。

The following suggestion let's you test abstract classes without creating a "real" subclass - the Mock is the subclass.

使用 Mockito.mock(My.class,Mockito.CALLS_REAL_METHODS),然后模拟任何被调用的抽象方法。

use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.

示例:

public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}

注意:这个解决方案的优点在于你做的不是来实现抽象方法,只要它们永远不会被调用。

Note: The beauty of this solution is that you do not have to implement the abstract methods, as long as they are never invoked.

在我看来,这比使用间谍更整洁,因为间谍需要一个实例,这意味着你必须创建一个抽象类的可实例化的子类。

In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiatable subclass of your abstract class.

这篇关于使用Mockito测试抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆