我正在尝试测试一个需要工厂(Func<T>
)的类,并且我正在使用 Moq 和 AutoFixture。
设置“环境”以查看工厂是否已使用以及在返回的实例上使用了多少次以及使用了哪些方法的最佳方法是什么?
目前我正在模拟T
和计算所有返回的模拟实例Injecting
:Func<T>
public class SystemUnderTest {
public SystemUnderTest(Func<IMyClass> c)
{
try {
var c1 = c();
c1.Name="n1";
c1.Send();
}
catch(Exception){
var c2 = c();
c2.Name="n2";
c2.Send();
}
}
}
private Mock<IMyClass> MockFactory()
{
var m = new Mock<IMyClass>();
m.SetupProperty(mc=>mc.Name);
_returnedStubs.Add(m);
return m;
}
[Test]
public void TestSomething()
{
var fixture = new Fixture();
fixture.Inject(()=>MockFactory().Object)
var sut = fixture.CreateAnonymous<SystemUnderTest>();
Assert.That(_returnedStubs.Count,Is.Equal(1));
_returnedStubs[0].Verify(m=>m.Send(),Times.Exactly(1));
_returnedStubs[0].Verify(m=>m.Name = "n1");
}
但这对我来说有点可疑/丑陋。而且我很确定测试类中的实例变量是一件危险的事情