vendredi 16 décembre 2016

Overriding AutoFac Registrations for unit testing entry point of application

Attempting to write tests for the entry of my application under specific error conditions - the entry looks similar too:

IFoo.cs

public interface IFoo
{
    void DoStuff();
}

Foo.cs

public class Foo : IFoo
{    
    void DoStuff()
    {
        // Do some things
    }
}

AutoFacConfig.cs

public class AutofacConfig
{
    private static IContainer _container;

    public static IContainer Container
    {
        get { return _container; }
    }

    public static void IoCConfiguration()
    {
        var builder = new ContainerBuilder();

        // Registrations...
        builder.RegisterType<Foo>();

        _container = builder.Build();
    }
}

Program.cs

public class Program
{
    public static int Main(string[] args)
    {
        try
        {
            AutofacConfig.IoCConfiguration();
            using (var scope = AutofacConfig.Container.BeginLifetimeScope())
            {
                var foo = scope.Resolve<Foo>();
                var result = foo.DoStuff());
            }
        }
        catch (Exception ex)
        {
            return 0;
        }

        return 1;
    }
}

Test.cs

[TestFixture]
public class Test
{
    [Test]
    public void ShouldReturn0WhenExceptionEncountered()
    {
        // How to override say, Foo.DoStuff to throw an exception?
        var result = Program.Main();

        Assert(0, result);
    }
}

The above is an oversimplified example, however it can be difficult to actually cause an exception through my real implementations that are registered through AutoFac. In order to test the entry point's catching of exceptions, it would be easier if i could inject a mock or fake of one of my dependencies within Foo.

How can I do this?

Aucun commentaire:

Enregistrer un commentaire