ExpectedException没有捕获异常,但是我可以用try catch捕获它
对此有什么想法吗?我正在尝试编写一个单元测试,该测试将删除一个项目并尝试通过按ID检索该项目(该项目应抛出DataAccessException)来确认该项目不在存储库中。但是,测试一直失败。我添加了一个try catch块,并确定已经捕获了我所期望的异常。我正在使用VS测试工具进行单元测试。
Any ideas on this one? I'm trying to write a unit test that will delete an item and confirm that item is no longer in a repository by trying to retrieve the item by its ID which should throw a DataAccessException. However, the test keeps failing. I added a try catch block and sure enough I caught the exception I was expecting. I'm using VS Test Tools for unit testing.
[ExpectedException(typeof(DataAccessException))]
private static void NHibernateRepositoryBaseDeleteHelper<T, TKey>(T myItem, TKey myItemId)
{
MyTestRepository<T, TKey> myRepository = new MyTestRepository<T, TKey>();
myRepository.Delete(myItem);
myRepository.CommitChanges();
try
{
myRepository.GetById(myItemId, false);
}
catch (DataAccessException dae)
{
Assert.IsTrue(true);
}
}
您需要将ExpectedException属性添加到具有TestMethod属性的同一方法上。 VS单元测试框架将仅在特定测试的入口点查找ExpectedException属性。
You need to add the ExpectedException attribute onto the same method which has the TestMethod attribute. The VS Unit Test Framework will only look for an ExpectedException attribute at the entry point of a particular test.
[TestMethod]
[ExpectedException(typeof(DataAccessException))]
public void ATestMethod() {
...
NHibernateRepositoryBaseDeleteHelper(itemValue, keyValue);
}