我尝试用 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 参数化测试,但我不确定这是否是我要找的。p>
非常感谢!
最佳答案
我使用以下模式针对我的接口(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/