如何为接口默认方法编写Junit [英] How to write Junit for Interface default methods

查看:71
本文介绍了如何为接口默认方法编写Junit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮忙为接口默认方法编写Junit.

Please help in writing Junit for the interface default method.

public interface ABC<T, D, K, V> {
    default List<String> getSrc(DEF def, XYZ xyz) throws Exception {
    }
}

ABC:接口名称. DEF和XYZ:类别名称

ABC: Interface Name. DEF and XYZ: Class Name

推荐答案

如果您使用的是 Mockito ,对默认方法(又称防御者")进行单元测试的最简单方法是制作一个

If you're using Mockito, the simplest way to unit-test a default (AKA "defender") method is to make a spy1 using the interface class literal2. The default method can then be invoked on the returned spy instance as normal. The following example demonstrates:

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;

interface OddInterface {
    // does not need any unit tests because there is no default implementation
    boolean doSomethingOdd(int i);

    // this should have unit tests because it has a default implementation
    default boolean isOdd(int i) {
        return i % 2 == 1;
    }
}

public class OddInterfaceTest {
    OddInterface cut = spy(OddInterface.class);

    @Test
    public void two_IS_NOT_odd() {
        assertFalse(cut.isOdd(2));
    }

    @Test
    public void three_IS_odd() {
        assertTrue(cut.isOdd(3));
    }
}

(已使用Java 8和 mockito-2.24.5 )

1 人们经常警告使用spy可以表示代码或测试气味,但是测试默认方法是使用spy的完美示例. 个主意.

1People often warn using a spy can be indicative of a code or test smell, but testing a default method is a perfect example of when using a spy is a good idea.

2 在撰写本文时(2019年),接受类文字的spy的签名被标记为@Incubating,但是自 mockito-1.10.12 .此外, Mockito中默认方法的支持. com/artifact/org.mockito/mockito-core/2.1.0"rel =" noreferrer> mockito-2.1.0 (于2016年发布).似乎可以肯定地说,此方法将继续有效在Mockito的未来版本中.

2As of the time of this writing (2019), the signature of spy which accepts a class literal is marked as @Incubating, but has been around since mockito-1.10.12 which was released in 2014. Furthermore, support for default methods in Mockito has been around since mockito-2.1.0 which was released in 2016. It seems like a safe bet that this method will continue to work in future versions of Mockito.

这篇关于如何为接口默认方法编写Junit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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