我正努力为我的一个课程进行单元测试。我想注入我的工厂,而不是autofac解决的自动生成的工厂。如何将自己的函数注册为代理以替换自动生成的委托工厂?
我的代码看起来像是大纲形式:
interface IEntryImporter { ... }
class EntryImporter : IEntryImporter {
public EntryImporter(ISeries series, IMatch match, Entry.Factory entryFactory) {
:
}
:
}
interface IEntry : { ... }
class Entry : IEntry {
public delegate IEntry Factory();
public Entry() { ... }
}
interface IMatch : { ... }
class Match : IMatch { ... }
interface ISeries : { ... }
class Series : ISeries { ... }
void IEntry MyEntryFactory() {
var entry = new Mock<IEntry>();
:
return entry.Object;
}
void TestMe() {
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Entry>().As<IEntry>();
builder.RegisterType<Match>().As<IMatch>();
builder.RegisterType<Series>().As<ISeries>();
builder.RegisterType<EntryImporter>.As<IEntryImporter>();
var series = new Mock<ISeries>(MockBehavior.Strict);
builder.RegisterInstance<ISeries>(series.Object);
var match = new Mock<IMatch>(MockBehavior.Strict);
builder.RegisterInstance<IMatch>(match.Object);
// How to register MyEntryFactory as Entry.Factory for autofac to resolve?
using(var container = builder.Build()) {
var importer = container.Resolve<IEntryImporter>();
:
}
}
答案 0 :(得分:6)
您可以注册自己的方法用作模拟条目工厂,如下所示:
builder.Register<Entry.Factory>(c => MyEntryFactory).As<Entry.Factory>();