Replacing [ExpectedException] in WinRT unit test library

Uncategorized

8 years ago

Recently I needed to write an unit test for my Windows Store application, that would check if a code snippet caused an expected exception. Usually this is done in the following manner:

[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public async Task Test()
{
  int result = ( new Calc() ).Divide( 3, 0 );
}

However, the Unit Test Library for WinRT lacks the ExpectedException attribute. Luckily, it was replaced by a far more convenient and useful method Assert.ThrowsException :

[TestMethod]
public async Task Test()
{
  Assert.ThrowsException<DivideByZeroException>( () => { new Calc() ).Divide( 3, 0 );} );
}

You need to provide the type of expected exception as the type parameter of this method and then a lambda expression (or Action instance), that contains the code that should throw the exception.