Search code examples
c#visual-studiounit-testingexception

ExpectedException not catching exception, but I can catch it with try catch


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);
        }
    }

Solution

  • 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);
    }