Testing Exceptions in Nunit 4.7

I am getting in TDD a lot, and of course, when thinking in border cases, you'll end up throwing exceptions, And you'd want to see ith they get thrown. With Nunit 4.7 the thing is that If, for example, you're testing that some parameter is null, when you decorate your test with [ExpectedException] it eventually gets thrown, but You'll never know what piece of code actually did it...
So, I created this little R# snippet to test excxeptions in a more granular way:
 
[Test]
public void $TestName$()
{
 try
 {
  $Code$
 }
 catch (Exception e)
 {
  Assert.That(e, Is.TypeOf(typeof($ExpectedException$)));
  $END$
  return;
 }
 Assert.Fail("Did Not Throw the Exception.");
}

For example, if you want to test if a parameter is null before you excercise some code, you could have a test like this:

[Test]
public void Intermediary_ParamOneCannotBeNull()
{
 try
 {
  new Intermediary(null, null);
 }
 catch(Exception e)
 {
  Assert.That(e, Is.TypeOf(typeof(ArgumentNullException)));
  Assert.That(((ArgumentNullException)e).ParamName, Is.EqualTo("paramOne"));
  return;
 }
 Assert.Fail("Did Not Throw the Exception.");
}


this code will not pass:

public Intermediary(IObject paramOne, IObject2 paramTwo
{
 if(paramtwo == null)
  throw new ArgumentNullException("company");
 _one = paramOne
 _two = paramTwo;
}


If you'd tested the code with ExpectedException, The code would had passed..

Of course, You could've used Nunit 5.0 ... :-)

Comments

Popular posts from this blog

Manejo de "Cumpleaños del mes" en WSS 3.0

Running Linux CMD in Windows - the RipGrep Case

Running Linux CMD in Windows - the webpack Case