views:

27

answers:

3

I don`t want to use the [ExpectedException(ExceptionType = typeof(Exception), ExpectedMessage = "")] instead would like to include the exception inside my method. Can I do that? Any example please.

Thanks

+1  A: 

Hi there.

Your question doesn't quite make sense. As a hunch, I guess you're asking about letting an exception be caught in your unit test, and then you can perform an assertion even though the exception has been raised?

[TestMethod]
public void Test1()
{
  try{
    // You're code to test.
  }
  catch(Exception ex){
   Assert.AreEqual(1, 1); // Or whatever you want to actually assert.
  }
}

EDIT:

Or

[TestMethod]
public void Test1()
{
  try{
    // You're code to test.
    AreEqual(1, 1); // Or whatever you want to actually assert.
  }
  catch(Exception ex){
   Assert.Fail();
  }
}

Cheers. Jas.

Jason Evans
your test doesn't fail when the exception is not thrown.
Stefan Steinegger
@Stefan - Have updated post. Cheers :)
Jason Evans
Ok, but it should be the other way around: fail at last line in try and assert in catch.
Stefan Steinegger
+5  A: 

Sometimes I want to test for the value of particular exception properties and in that case I sometimes choose to not use the ExpectedException attribute.

Instead I use the following approach (an example):

[Test]
public void MyTestMethod() {
   try {
      var obj = new MyClass();
      obj.Foo(-7); // Here I expect an exception to be thrown
      Assert.Fail(); // in case the exception has not been thrown
   }
   catch(MySpecialException ex) {
      // Exception was thrown, now I can assert things on it, e.g.
      Assert.AreEqual(-7, ex.IncorrectValue);
   }
}
John
A: 

something like this:

[TestMethod]
public void FooTest()
{
  try
  {
    // run test
    Assert.Fail("Expected exception had not been thrown");
  }
  catch(Exception ex)
  {
    // assert exception or just leave blank
  }
}
Stefan Steinegger