Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock the autofac's autogenerated delegate factories?

I'm struggling to get a unit test working for one of my classes. I want to inject my factory instead of the autogenerated factory the autofac resolves to. How do I register my own function as the delegate to replace the autogenerated delegate factory?

My code looks something like this is outline form:

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>();
        :
    }
}
like image 536
Ants Avatar asked Jun 13 '11 07:06

Ants


1 Answers

You can register your own method for use as the mock entry factory as follows:

builder.Register<Entry.Factory>(c => MyEntryFactory).As<Entry.Factory>();

I have got your sample working as part of Autofac Answers on GitHub.

like image 91
bentayloruk Avatar answered Nov 12 '22 01:11

bentayloruk