testing - 在没有实现的情况下针对接口(interface)进行 JUnit 测试

标签 testing interface junit mockito

我尝试用 JUnit 为给定的接口(interface)编写测试,但不知道该怎么做:

public interface ShortMessageService {

    /**
     * Creates a message. A message is related to a topic
     * Creates a date for the message
     * @throws IllegalArgumentException, if the message is longer then 255 characters.
     * @throws IllegalArgumentException, if the message ist shorter then 10 characters.
     * @throws IllegalArgumentException, if the user doesn't exist
     * @throws IllegalArgumentException, if the topic doesn't exist
     * @throws NullPointerException, if one argument is null.
     * @param userName
     * @param message
     * @return ID of the new created message
     */
    Long createMessage(String userName, String message, String topic);

    [...]
}

在我意识到它根本没有意义之后,我尝试模拟界面,所以我有点迷茫。也许有人可以给我一个我可以使用的好方法。我还听说过 junit 参数化测试,但我不确定这是否是我要找的。

非常感谢!

最佳答案

我使用以下模式针对我的接口(interface) API 编写抽象测试,但没有任何可用的实现。您可以在 AbstractShortMessageServiceTest 中编写所需的任何测试,而无需在那个时间点实现它们。

public abstract class AbstractShortMessageServiceTest
{
    /**
     * @return A new empty instance of an implementation of FooManager.
     */
    protected abstract ShortMessageService getNewShortMessageService();

    private ShortMessageService testService;

    @Before
    public void setUp() throws Exception
    {
        testService = getNewShortMessageService();
    }

    @Test
    public void testFooBar() throws Exception 
    {
        assertEquals("question", testService.createMessage(
                                             "DeepThought", "42", "everything"));
    }
}

有了实现后,只需定义一个覆盖 AbstractShortMessageServiceTest 并实现 getNewShortMessageService 方法的新测试类即可使用测试。

public class MyShortMessageServiceTest extends AbstractShortMessageServiceTest
{
    protected ShortMessageService getNewShortMessageService()
    {
        return new MyShortMessageService();
    }
}

此外,如果您需要对测试进行参数化,您可以在 AbstractShortMessageServiceTest 中执行此操作,而无需在每个具体测试中执行。

关于testing - 在没有实现的情况下针对接口(interface)进行 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20599862/

相关文章:

testing - 删除 Clojure REPL 中定义的测试

php - 贝哈特和水貂 : Use the test environment

python - 如何运行 python 测试套件?

c# - 在c#中获取底层接口(interface)的属性

android - UiAutomator 测试套件(一组测试)

java - 如何在 android 测试中监听 Android ActivityTestRule 的 beforeActivityLaunched 方法

testing - 出现故障时重新启动夹具

c++ - 使用抽象类的容器来容纳子类

c# - 合并两个实现相同接口(interface)的类列表

java - 在 JUnit 参数化测试中使用非静态注入(inject)服务