chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes

I have a simple method that throws and exception, i want to test any scenario of it.
The case when the Exception is thrown is simple, I assert it was thrown,

But how can I assert the second case when it is not thrown?
An example of my method?

public void Validate(string userName, string password)

{

if (null == userName || null == password)

{

throw new ArgumentNullException();

}

             }

asked by (4.8k points)

1 Answer

0 votes

You can create a test for the 2nd case, and it is OK to not have an assert in the test. It is because the test will pass when no exception is thrown, and it will fail when an exception is thrown. Sample code attached below.

For details please check Typemock resource What if I’m just testing that no exception is being thrown? section in https://www.typemock.com/always-assert-something/.

Btw, it seems NUnit supports Assert.DoesNotThrow which makes the test code more readable, but not sure if you could use NUnit. Ref: https://stackoverflow.com/a/23062325

Please let me know if you need further help or clarification. Good luck!

[TestMethod]
public void Validate_Called_DoesNotThrowException()
{
    // Arrange
    string userName = string.Empty;
    string password = string.Empty;

    // Act
    MyCode.Validate(userName, password)

    // No assert because we expect no exception is being thrown
}
answered ago by (140 points)
...