は、私にはよく指定されたインターフェイスを持っており、それに対して私は私のJUnitテストを書く:1つのテストメソッドで複数のスローされた例外をテストできますか?
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);
[...]
}
あなたは実装が、私がテストを書くために持っているため、さまざまな例外をスローすることができます見ることができるように。今、私はインターフェイスで定義された1つの方法のための試験方法の多くを定義する必要があり、それは感じているためだから
public abstract class AbstractShortMessageServiceTest
{
String message;
String username;
String topic;
/**
* @return A new empty instance of an implementation of ShortMessageService.
*/
protected abstract ShortMessageService getNewShortMessageService();
private ShortMessageService messageService;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() throws Exception
{
messageService = getNewShortMessageService();
message = "Test Message";
username = "TestUser";
topic = "TestTopic";
}
@Test
public void testCreateMessage()
{
assertEquals(new Long(1L), messageService.createMessage(username, message, topic));
}
@Test (expected = IllegalArgumentException.class)
public void testCreateMessageUserMissing() throws Exception
{
messageService.createMessage("", message, topic);
}
@Test (expected = IllegalArgumentException.class)
public void testCreateMessageTopicMissing() throws Exception
{
messageService.createMessage(username, message, "");
}
@Test (expected = IllegalArgumentException.class)
public void testCreateMessageTooLong() throws Exception
{
String message = "";
for (int i=0; i<255; i++) {
message += "a";
}
messageService.createMessage(username, message, topic);
}
@Test (expected = IllegalArgumentException.class)
public void testCreateMessageTooShort() throws Exception
{
messageService.createMessage(username, "", topic);
}
@Test (expected = NullPointerException.class)
public void testCreateMessageNull() throws Exception
{
messageService.createMessage(username, null, topic);
}
[...]
}
:私の現在のアプローチは、このようなインターフェイスに指定された一つの可能な例外の一つの試験方法を書くことです厄介です。これらの例外テストをすべて1つのテスト方法で組み合わせたり、ベストプラクティスを組み合わせることはできますか?
これは良いですが、あなたはExpectedExceptionルールを使用して、これを向上させることができます。https://github.com/junit-team/junit/blob/master/src/main/java/org/junit /rules/ExpectedException.java –