在很多TDD教程中,我看到这样的代码:
public class MyClass
{
public void DoSomething(string Data)
{
if (String.IsNullOrWhiteSpace(Data))
throw new NullReferenceException();
}
}
[Test]
public DoSomething_NullParameter_ThrowsException()
{
var logic = MyClass();
Assert.Throws<NullReferenceException>(() => logic.DoSomething(null));
}
Run Code Online (Sandbox Code Playgroud)
这一切都有意义,但在某些时候你将会到达实际使用MyClass的类,并且你想测试异常是否被处理:
public class EntryPointClass
{
public void DoIt(string Data)
{
var logicClass = new MyClass();
try
{
logicClass.DoSomething(Data);
}
catch(NullReferenceException ex)
{
}
}
}
[Test]
public DoIt_NullParameter_IsHandled()
{
var logic = new EntryPointClass()
try
{
logic.DoIt(null);
}
catch
{
Assert.Fail();
}
}
Run Code Online (Sandbox Code Playgroud)
那么为什么不把my/class中的try/catch放在首先,而不是抛出异常,并在MyClass单元测试类中测试为null,而不是在EntryPointClass单元测试类中?