我正在尝试测试一个类的行为,当它通过委托工厂传递一个存根对象时。我制作了一个测试版本,其中所有类的依赖项(工厂除外)都作为 Mock 对象传递,并且它按预期工作。现在我正在尝试使用 AutoMock 让容器自动创建模拟。
我在使用 mock.Provide() 在 ClassUnderTest 的构造函数中传递委托工厂的具体值时遇到问题。(就像这个评论所暗示的)
我正在测试的课程:
public ClassUnderTest
{
private readonly firstField;
private readonly Func<string, ISecondField, IThirdField, IResultField> resultFieldFactory;
private int someCounter = -1;
public ClassUnderTest(IFirstField firstField, Func<string, ISecondField, IThirdField, IResultField> resultFieldFactory )
{
this.firstField = firstField;
this.resultFieldFactory= resultFieldFactory;
}
public methodToTest()
{
IResultField resultField = resultFieldFactory(someString, secondFieldValue, thirdFieldValue);
resultField.AddToList();
}
}
业务逻辑模块:
public class BusinessLogicModule: Module
{
//some other things that work
builder.RegisterType<ClassUnderTest>().As<IClassUnderTest>();
builder.RegisterType<SecondField>().As<ISecondField>();
builder.RegisterType<ThirdField>().As<IThirdField>();
builder.RegisterType<ResultField>().As<IResultField>();
}
测试类:
[TestClass]
public class TestClass()
{
private IFirstField firstField;
private Func<string, ISecondField, IThirdField, IResultField> funcToTriggerIResultFieldFactory;
[TestInitialize]
public void Setup()
{
this.firstField= Resolve<IFirstField>();
this.secondField= Resolve<ISecondField>();
this.funcToTriggerIResultFieldFactory = Resolve<Func<string, ISecondField, IThirdField, IResultField>>();
}
[TestMethod]
public void testMethodWithAutoMock()
{
using (var automock = AutoMock.GetLoose())
{
//trying to setup the SUT to get passed a "concrete" object
autoMock.Provide(funcToTriggerIResultFieldFactory(stringValue, secondFieldValue, thirdFieldValue));
var sut = autoMock.Create<IClassUnderTest>;
sut.MethodToTest();
//asserts
}
}
}
如果有任何迹象表明我做错了什么,我将不胜感激。我错过了什么?怎么可能修好?这是一个简单的语法修复还是我的测试方法有问题?
在此先感谢您的时间。