我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
这适用于Visual Studio Team Test(又名MSTest) 在处理数据库或http事务时。系统应该在某处抛出异常,使用Assert.ThrowExceptionAsync<>()将捕获您的throw事件。(在这些情况下,Assert.ThrowException<>()不会捕获异常)。
[TestMethod]
public void Invalid_Input_UserName_Should_Throw_Exception()
{
await Assert.ThrowExceptionAsync<ExpectedExceptionType>(()=> new LogonInfo(InvalidInputInUserNameFormat,"P@ssword"));
}
其他回答
既然您提到了使用其他测试类,那么比ExpectedException属性更好的选择是使用Shoudly的Should.Throw。
Should.Throw<DivideByZeroException>(() => { MyDivideMethod(1, 0); });
假设我们有一个需求,客户必须有一个地址才能创建订单。如果不是,CreateOrderForCustomer方法应该导致一个ArgumentException。那么我们可以这样写:
[TestMethod]
public void NullUserIdInConstructor()
{
var customer = new Customer(name := "Justin", address := null};
Should.Throw<ArgumentException>(() => {
var order = CreateOrderForCustomer(customer) });
}
这比使用ExpectedException属性更好,因为我们明确了应该抛出错误的内容。这使得测试中的需求更加清晰,并且在测试失败时更容易诊断。
注意这里还有一个Should。ThrowAsync用于异步方法测试。
Even though this is an old question, I would like to add a new thought to the discussion. I have extended the Arrange, Act, Assert pattern to be Expected, Arrange, Act, Assert. You can make an expected exception pointer, then assert it was assigned to. This feels cleaner than doing your Asserts in a catch block, leaving your Act section mostly just for the one line of code to call the method under test. You also don't have to Assert.Fail(); or return from multiple points in the code. Any other exception thrown will cause the test to fail, because it won't be caught, and if an exception of your expected type is thrown, but the it wasn't the one you were expecting, Asserting against the message or other properties of the exception help make sure your test won't pass inadvertently.
[TestMethod]
public void Bar_InvalidDependency_ThrowsInvalidOperationException()
{
// Expectations
InvalidOperationException expectedException = null;
string expectedExceptionMessage = "Bar did something invalid.";
// Arrange
IDependency dependency = DependencyMocks.Create();
Foo foo = new Foo(dependency);
// Act
try
{
foo.Bar();
}
catch (InvalidOperationException ex)
{
expectedException = ex;
}
// Assert
Assert.IsNotNull(expectedException);
Assert.AreEqual(expectedExceptionMessage, expectedException.Message);
}
如果你使用NUNIT,你可以这样做:
Assert.Throws<ExpectedException>(() => methodToTest());
也可以存储抛出的异常以便进一步验证:
ExpectedException ex = Assert.Throws<ExpectedException>(() => methodToTest());
Assert.AreEqual( "Expected message text.", ex.Message );
Assert.AreEqual( 5, ex.SomeNumber);
参见:http://nunit.org/docs/2.5/exceptionAsserts.html
在我正在做的一个项目中,我们有另一个解决方案。
首先,我不喜欢ExpectedExceptionAttribute,因为它确实考虑了导致异常的方法调用。
我用一个helper方法来代替它。
Test
[TestMethod]
public void AccountRepository_ThrowsExceptionIfFileisCorrupt()
{
var file = File.Create("Accounts.bin");
file.WriteByte(1);
file.Close();
IAccountRepository repo = new FileAccountRepository();
TestHelpers.AssertThrows<SerializationException>(()=>repo.GetAll());
}
HelperMethod
public static TException AssertThrows<TException>(Action action) where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
return ex;
}
Assert.Fail("Expected exception was not thrown");
return null;
}
很整洁,不是吗?)
使用ExpectedException时要谨慎,因为它可能导致如下所示的几个陷阱:
Link
在这里:
http://xunit.github.io/docs/comparisons.html
如果需要测试异常,有一些不太受欢迎的方法。您可以使用try{act/fail}catch{assert}方法,该方法对于除了ExpectedException之外不直接支持异常测试的框架非常有用。
更好的选择是使用xUnit。NET,这是一个非常现代的、前瞻性的、可扩展的单元测试框架,它已经从所有其他错误中吸取了教训,并进行了改进。Assert就是这样一种改进。它为断言异常提供了更好的语法。
你可以找到xUnit。NET在github: http://xunit.github.io/