无论出于何种原因,我似乎无法获得正确的语法。 您如何进行以下测试。我只有一个简单的方法 TestThrowexception 并希望它通过 我在这里做错了什么?
[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)
{
}
}
}
最佳答案
除了您抛出的异常类型的问题外,我会这样做。我认为它更具可读性。
[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");
}
关于c# - 无法使 nunit 测试异常起作用。使用 .net 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6772990/