2015-11-24 22 views
31

.NET Framework üzerinde Test Araçları'nı kullanmak için yeni konum, bu yüzden ReSharper'ın yardımıyla NuGet'ten karşıdan yükledim.nUnit içinde ExpectedException bana bir hata verdi

nUnit kullanmayı öğrenmek için bu Quick Start kullanıyorum. Ben sadece kod kopyaladığı ve bir hata Bu özellik hakkında geldi:

[ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception 

hatadır:

tür veya ad alanı adı 'ExpectedException' bulunamadı (bir eksik direktif ya da bir montaj referansı kullanarak?)

Neden? Ve eğer böyle bir işlevselliğe ihtiyacım varsa, onu ne ile değiştirmeliyim?

+0

Hangi hata görüntüleniyor? Hata nUnit veya IDE'nizde gösteriliyor mu? – Chawin

+0

Kodunuzun InsufficientFundsException olmayan bir istisna döndürdüğünü düşünüyorum –

cevap

54

NUnit 3.0 kullanıyorsanız, hatanın nedeni ExpectedExceptionAttributehas been removed. Bunun yerine Throws Constraint gibi bir yapı kullanmalısınız.

Örneğin

, bağlantılı öğretici bu testi vardır:

[Test] 
[ExpectedException(typeof(InsufficientFundsException))] 
public void TransferWithInsufficientFunds() 
{ 
    Account source = new Account(); 
    source.Deposit(200m); 

    Account destination = new Account(); 
    destination.Deposit(150m); 

    source.TransferFunds(destination, 300m); 
} 

, NUnit 3.0 altında çalışmak üzere bunu değiştirmek için değiştirmek için aşağıdakileri yapın:

[Test] 
public void TransferWithInsufficientFunds() 
{ 
    Account source = new Account(); 
    source.Deposit(200m); 

    Account destination = new Account(); 
    destination.Deposit(150m); 

    Assert.That(() => source.TransferFunds(destination, 300m), 
       Throws.TypeOf<InsufficientFundsException>()); 
} 
4

Hala kullanmak isterseniz Öznitelikleri şu şekilde düşünün:

[TestCase(null, typeof(ArgumentNullException))] 
[TestCase("this is invalid", typeof(ArgumentException))] 
public void SomeMethod_With_Invalid_Argument(string arg, Type expectedException) 
{ 
    Assert.Throws(expectedException,() => SomeMethod(arg)); 
} 
11

Bu durumun son zamanlarda değişip değişmediğinden emin değilsiniz ancak NUnit 3.4.0 ilesağlar..

[Test] 
public void TransferWithInsufficientFunds() { 
    Account source = new Account(); 
    source.Deposit(200m); 

    Account destination = new Account(); 
    destination.Deposit(150m); 

    Assert.Throws<InsufficientFundsException>(() => source.TransferFunds(destination, 300m)); 
} 
İlgili konular