ExpectedException没有捕获异常,但是我可以用try catch捕获它 [英] ExpectedException not catching exception, but I can catch it with try catch

查看:137
本文介绍了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);
}

这篇关于ExpectedException没有捕获异常,但是我可以用try catch捕获它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆