我正在对具有依赖关系的服务方法进行单元测试。简化:
public class ConditionChecker
{
private SqlConnection _connection;
public bool CanDoSomething()
{
return _connection.State == ConnectionState.Open;
}
}
public class A
{
public ConditionChecker Checker { get; set; }
public bool CanInvokeA()
{
return Checker.CanDoSomething();
}
}
[TestClass]
public class ATests
{
[TestMethod]
public void TestCanInvokeA()
{
// arrange
A a = new A();
ConditionChecker checker = MockRepository.GenerateStub<ConditionChecker>();
checker.Stub(x => x.CanDoSomething()).Return(true);
a.Checker = checker;
// act
bool actual = a.CanInvokeA();
// assert
Assert.AreEqual(true, actual);
}
}
我想要的是完全绕过 的实现ConditionChecker.CanDoSomething
,这就是我存根调用的原因,但我在测试期间仍然遇到空引用异常,因为_connection
未设置成员。我在这里做错了什么?