Search code examples
c#.netunit-testingmicrosoft-unit-testing

How to test Assert for base class exception implementation using Microsoft Unit testing framework?


Here is specific case. I want to test this Assert.ThrowsException<DbException>(() => { MyMethod(0, 100); });

The problem is that exception thrown is SqlException. Why do I want to test base exception? Because I want a unified test for any of my 3 DB providers. The exception sometimes is OracleException or MySqlException. All 3 providers exceptions derive from DbException

Is there a way to test it nicely, using the Microsoft Unit Test framework?


Solution

  • Thanks for all the leads, one from @StephanAdler

    Considering limitations of given testing framework my sensible solution was this

    Exception retEx = null;
    
    try
    {
        MyMethod(0, 100);
    }
    catch (Exception ex)
    {
        retEx = ex;
    }
    
    Assert.IsNotNull(retEx);
    Assert.IsInstanceOfType(retEx, typeof(DbException));
    
    

    Assert.IsInstanceOfType works perfectly with the base type