我不想使用[ExpectedException(ExceptionType = typeof(Exception),ExpectedMessage =“”)],而是想在我的方法中包含异常。我可以这样做吗?请任何例子。如何包含内部方法
谢谢
我不想使用[ExpectedException(ExceptionType = typeof(Exception),ExpectedMessage =“”)],而是想在我的方法中包含异常。我可以这样做吗?请任何例子。如何包含内部方法
谢谢
是这样的:
[TestMethod]
public void FooTest()
{
try
{
// run test
Assert.Fail("Expected exception had not been thrown");
}
catch(Exception ex)
{
// assert exception or just leave blank
}
}
你的问题不太合理。作为一种预感,我猜你在问单元测试中是否会遇到异常,然后即使异常已被提出,也可以执行断言?
[TestMethod]
public void Test1()
{
try{
// You're code to test.
}
catch(Exception ex){
Assert.AreEqual(1, 1); // Or whatever you want to actually assert.
}
}
编辑:
或者
[TestMethod]
public void Test1()
{
try{
// You're code to test.
AreEqual(1, 1); // Or whatever you want to actually assert.
}
catch(Exception ex){
Assert.Fail();
}
}
有时候我想测试特定的异常性的价值,在这种情况下我有时会选择不使用的ExpectedException属性。
相反,我用下面的办法(例子):
[Test]
public void MyTestMethod() {
try {
var obj = new MyClass();
obj.Foo(-7); // Here I expect an exception to be thrown
Assert.Fail(); // in case the exception has not been thrown
}
catch(MySpecialException ex) {
// Exception was thrown, now I can assert things on it, e.g.
Assert.AreEqual(-7, ex.IncorrectValue);
}
}
在不引发的异常测试不会失败。 – 2010-08-12 11:31:23
@Stefan - 已更新帖子。干杯:) – 2010-08-12 11:34:40
好吧,但它应该是另一种方式:在尝试和失败的最后一行失败。 – 2010-08-12 11:43:37