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

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

问题描述

我想测试一个抽象类.当然,我可以手动编写一个从类继承的模拟.>

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

解决方案

以下建议让您无需创建真正的"子类即可测试抽象类 - Mock 是子类.

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

示例:

公共抽象类我的{公共结果 methodUnderTest() { ... }受保护的抽象无效方法IDontCareAbout();}公共类 MyTest {@测试public void shouldFailOnNullIdentifiers() {My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);Assert.assertSomething(my.methodUnderTest());}}

注意:这个解决方案的美妙之处在于您不必实现抽象方法,只要它们从不被调用.

老实说,这比使用 spy 更简洁,因为 spy 需要一个实例,这意味着您必须创建抽象类的可实例化子类.

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

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.

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

Example:

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天全站免登陆