SORU
1 EKİM 2008, ÇARŞAMBA


Nasıl belirli bir durum JUnit 4 Test atılmış olduğunu iddia musunuz?

Nasıl bazı kod bir özel durum oluşturduğunda JUnit4 idiomatically test etmek için kullanabilir miyim?

Kesinlikle böyle bir şey yapabilirim:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
  boolean thrown = false;

  try {
    foo.doStuff();
  } catch (IndexOutOfBoundsException e) {
    thrown = true;
  }

  assertTrue(thrown);
}

Bir açıklama veya bir İddia olduğunu bildirdi.xyz yabir şeybu çok daha az kludgy ve çok daha bu tarz olayları için JUnit of-the-spirit.

CEVAP
29 Mayıs 2010, CUMARTESİ


JUnit ExpectedException Kural kullanabilirsiniz 4.7, kullanabilirsiniz

public class FooTest {
  @Rule
  public final ExpectedException exception = ExpectedException.none();

  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    exception.expect(IndexOutOfBoundsException.class);
    foo.doStuff();
  }
}

Bu test eğer IndexOutOfBoundsException foo.doStuff() önce atılır başarısız olur, çünkü @Test(expected=IndexOutOfBoundsException.class) göre çok daha iyi

Ayrıntılar için this article bkz

Düzenleme:Eğer Java 8, Rafal answer bak. kullanıyorsanız

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Lupe Fiasco

    Lupe Fiasco

    23 ŞUBAT 2006
  • Tips On Linux

    Tips On Linu

    26 Temmuz 2008
  • Troy Hunt

    Troy Hunt

    29 EYLÜL 2011