对没有实现的接口的JUnit测试

chi*_*ult 3 testing junit interface mockito

我尝试用JUnit编写一个给定接口的测试,并且不知道如何做到这一点:

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);

    [...]
}
Run Code Online (Sandbox Code Playgroud)

在我意识到它完全没有意义之后我试图模仿界面,所以我有点迷失.也许有人可以给我一个我可以合作的好方法.我也听说过junit参数化测试,但我不确定这是不是我要找的.

非常感谢!

Pet*_*ter 5

我使用以下模式为我的接口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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

有了实现时,只需定义一个覆盖AbstractShortMessageServiceTest并实现getNewShortMessageService方法的新测试类,就可以使用测试.

public class MyShortMessageServiceTest extends AbstractShortMessageServiceTest
{
    protected ShortMessageService getNewShortMessageService()
    {
        return new MyShortMessageService();
    }
}
Run Code Online (Sandbox Code Playgroud)

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