我正在尝试测试类的行为,当它通过委托工厂传递一个存根对象时。我做了一个测试版本,其中所有类的依赖项(工厂除外)都作为Mock对象传递,它按预期工作。现在我尝试使用AutoMock让容器自动创建模拟。
我在使用mock.Provide()在ClassUnderTest的构造函数中传递委托工厂的具体值时出现问题。 (如this comment建议)
我正在测试的课程:
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
}
}
}
如果我做错了什么迹象,我将不胜感激。我错过了什么?怎么可能修好?这是一个简单的语法修复还是我的测试方法有问题?
提前感谢您的时间。
答案 0 :(得分:0)
在您的示例中,当您调用autoMock.Provide()
时,您没有传入工厂函数,但是您正在调用工厂函数并传入结果(IResultField
)。要解决此问题,请致电
autoMock.Provide(funcToTriggerIResultFieldFactory);
Here是使用自动模拟容器注册函数的完整示例。