If your framework does not support custom casting, you usually have two options:
- Implement it yourself
- Change (or expand) the structure
I will start with the second solution. Consider using the FluentAssertions library. This allows you to do something like this:
Action deleteUser = () => usersRepository.Delete(new User { Id = null }); deleteUser .ShouldThrow<UserNotFoundException>() .WithInnerException<ArgumentNullException>() .WithInnerMessage("User Id must have value");
You will continue to use the Visual Studio testing environment, you just have one additional library for well-spoken statements.
On the other hand, the first choice is a bit more work, as is usually the case with manually untwisted solutions:
try { usersRepository.Delete(new User { Id = null }); Assert.Fail("Deleting user with null id should throw"); } catch (UserNotFoundException ue) { Assert.AreEqual(ue.InnerException.Message, "User Id must have value"); }
The ExpectedException attribute is replaced with user code that confirms the actual instance of the exception. As I said, this is more work, but it does its job.
km
source share