2011-07-21 44 views
2

無論出於什麼原因,我似乎無法獲得正確的語法。 你如何進行以下測試工作。我只是有一個簡單的方法TestThrowexception,並希望它通過 我在這裏做錯了什麼?無法使nunit測試異常工作。使用.net 2.0

  [TestFixture] 
      public class ExceptionsTests 
      {  
       [Test] 
       public void When_calling_my_method_it_should_throw_an_exception() 
       { 
       //THIS DOES NOT WORK 
        Person person=new Person(); 

        PersonException ex = Assert.Throws<PersonException>(delegate { person.ThrowPersonException(); }, 
                  Has.Property("Message").EqualTo("Test person Exception throw")); 

       } 
      } 

      public class Person 
      { 
       public void ThrowException() 
       { 
        throw new Exception("Test Exception thrown"); 
       } 
       public void ThrowPersonException() 
       { 
        throw new CustomerException("Test person Exception thrown"); 
       } 


       public void ThrowArgumentException(string myParam) 
       { 
        throw new ArgumentException("Argument Exception", myParam); 
       } 
      } 
      [Serializable] 
      public class PersonException : Exception 
      { 

       public PersonException() 
       { 
       } 

       public PersonException(string message) 
        : base(message) 
       { 
       } 

       public PersonException(string message, Exception inner) 
        : base(message, inner) 
       { 
       } 

       protected PersonException(
        SerializationInfo info, 
        StreamingContext context) 
        : base(info, context) 
       { 
       } 
      } 
     } 

回答

0

除了拋出異常類型的問題,我會這樣做。我認爲它更具可讀性。

[Test] 
public void When_calling_my_method_it_should_throw_an_exception() 
{ 
    Person person=new Person(); 
    PersonException ex = Assert.Throws<PersonException>(delegate { person.ThrowPersonException(); }); 
    Assert.That(ex.Message,Is.EqualTo("Test person Exception thrown"); 
} 
+0

非常感謝這個例子。它是我嘗試過的另一個例子的複製和粘貼。現在所有的作品。謝謝 – user9969

0

你扔CustomerException而是奢望一段PersonException。你試着匹配兩個不同的字符串(「拋出」與「扔」)。

0

另一種測試異常的方法是在測試方法上使用ExpectedException屬性。 IMO更具可讀性。一切都取決於你的作品。

[Test] 
[ExpectedException(typeof(PersonException), ExpectedMessage = "Test person Exception thrown")] 
public void When_calling_my_method_it_should_throw_an_exception() 
{ 
    Person person=new Person(); 
    person.ThrowPersonException(); 
}