Note that there are some explanatory texts on larger screens.

plurals
  1. PO[ExpectedException(typeof(AnExceptionBaseException))]
    primarykey
    data
    text
    <p>I wrote a unit test in such a way that it <em>should</em> throw <code>AnException</code> or <code>AnotherException</code>, both deriving from <code>AnExceptionBaseException</code>. I then proceeded to add an <code>ExpectedExceptionAttribute</code> for the base exception, only to find that my test will still be marked as failed.</p> <blockquote> <p>Test Name: Call_Should_Throw_If_Device_Is_Not_Ready Test</p> <p>...</p> <p>Result Message: Test method DiskManagementTests.DiskFreeSpaceTests.Call_Should_Throw_If_Device_Is_Not_Ready threw exception System.IO.FileNotFoundException, but exception System.IO.IOException was expected. Exception message: System.IO.FileNotFoundException: The device is not ready. (Exception from HRESULT: 0x80070015)</p> </blockquote> <p>This seems like a reasonable design decision because, in this particular case, the exception is generated from an HRESULT return code. That makes it nearly impossible to determine which exception will be thrown. At least not without copying the code logic from the unit that my test is supposed to ...test.</p> <p>My code (I believe this can throw either <code>FileNotFound</code> or <code>DirectoryNotFound</code>):</p> <pre><code>[TestMethod] [ExpectedException(typeof(IOException))] public void Call_Should_Throw_If_Device_Is_Not_Ready() { foreach (DriveInfo drive in DriveInfo.GetDrives().Where(drive =&gt; !drive.IsReady)) { DiskFreeSpace diskFreeSpace = DiskManagement.GetDiskFreeSpace(drive.RootDirectory.FullName); Assert.Fail("API call did not fail even though the drive reports that it is not ready."); } Assert.Inconclusive("All drives were ready. Try testing with an empty disc drive."); } </code></pre> <p>Do I need to reconsider the way I write unit tests?</p> <p><strong>EDIT</strong></p> <p>This scenario is supported after all. All it really took was setting <code>AllowDerivedTypes</code> to true.</p> <pre><code>[TestMethod] [ExpectedException(typeof(IOException), AllowDerivedTypes = true)] public void Call_Should_Throw_If_Device_Is_Not_Ready() { // ... } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload