Let’s say I have a function that accepts a user name and password, it then retrieves the record from a database and performs the following checks on that data
- Today’s date is outside a date range
- User is disabled
- A parameter comparison is made
If any of these conditions are true an exception is thrown.
Obviously I want to write my unit test to test his logic, however if I do an exception will be thrown and my test will fail, which isn’t correct – is it?
Yes, your test will correctly throw an exception, but in most (all?) test frameworks you can specify the expected exception and the test will pass.
In MSTest and NUnit
Just be wary of cases where exceptions might be thrown but for reasons other than those you expect.