Ben iyi belirtilen arayüze sahip ve buna karşı benim JUnit testleri yazmak:Bir test yönteminde çoklu atılan istisnaları test edebilir miyim?
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);
[...]
}
Eğer uygulama Testleri yazmak zorunda olduğu için çeşitli istisnalar atabilir görebileceğiniz gibi. Ben arabirimde tanımlanan bu bir yöntem için test yöntemlerinin bir sürü tanımlamak zorunda ve hissediyor Yani şimdilik
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);
}
[...]
}
: My mevcut yaklaşımın böyle arayüzde belirtilen olası bir istisna için bir test yöntemi yazmaktır garip. Tüm bu istisna testlerini bir test yönteminde birleştirebilir miyim veya en iyi uygulama hangisidir?
Bu iyidir, ama sen ExpectedException kuralını kullanarak bu iyileştirebilir: https://github.com/junit-team/junit/blob/master/src/main/java/org/junit /rules/ExpectedException.java –