Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a .NET test method to fail from the inside

Most of my test methods first try two or three trivial operations which should raise an exception, and then begin the real work. In Java, I would write it like this:

@Test
public void TestSomething() {

    try {
        testedClass.testedMethod(null);
        fail();
    catch (IllegalArgumentException ex) {
        // OK
    }

    // and now let's get to the point ...
    // ...

} 

I wanted to stick with this habit in C#, but it seems there is no way to force a test method to fail. I've been looking a round for a while, but with no luck. Have I missed something?

PS: I know the correct way of testing these situations is this:

[TestMethod]
[ExpectedException(ArgumentNullException)]
public void TestSomethingWithNull() {

    testedClass.TestedMethod(null);

}

[TestMethod]
public void TestSomething() {

   // now the non-trivial stuff...

}

...but, I don't like this. When I have, let's say, 6 test methods in my test class, and each of those tests should start with covering three trivial, one-line situations which should raise an exception, using this approach turns my 6 tests into 18. In a bigger application, this really pollutes my Test Explorer and makes the results more difficult to scan through.

And let's say I want to test a method, whose responsibility is to validate each property of a given instance of some class, and raise a ValidationException if any value is incorrect. That could be easily handled by one TestValidation() test, but with this approach, turns it into:

  • TestValidationWithNull();
  • TestValidationWithInvalidProperty1();
  • TestValidationWithInvalidProperty2();
  • TestValidationWithNullProperty2();

Imagine you have 20 properties... :)

Of course, if this is the only way to do it, I'll bite.

like image 552
oli.G Avatar asked Jan 21 '26 03:01

oli.G


2 Answers

You can use Assert.Fail() or throw NotImplementedException (if method which you are testing is not implemented yet).

But for testing if code throws exception I suggest you to use ExpectedException attribute (if you are stick to MSTest) - test will fail, if exception will not be thrown.

like image 182
Sergey Berezovskiy Avatar answered Jan 23 '26 17:01

Sergey Berezovskiy


You need

Assert.Fail("Optional Message");

or you can just throw an exception from inside the method

You should also check out the TestCase attribute and TestCaseSource in NUnit. These might greatly simplify your code & testing when you want to pass different parameters to a test.

like image 43
Dr. Andrew Burnett-Thompson Avatar answered Jan 23 '26 16:01

Dr. Andrew Burnett-Thompson