try-catch-FAIL

Failure is inevitable

NAVIGATION - SEARCH

SpecsFor 3.1.0 Released

I shipped a small update to SpecsFor yesterday.  This update exposes the underlying mocking container to behaviors that are registered using the compositional context API.

Now you can do things like modify the container’s configuration from any behavior class.  We could specify that any dependency on some type should be resolved with a concrete type instead of a mocked instance, like so:

public interface IDatabaseSpecs : ISpecs
{
    //Stuff...
}

public class DatabaseFactory : Behavior<IDatabaseSpecs>
{
    public override void SpecInit(IDatabaseSpecs instance)
    {
        instance.MockContainer.Configure(cfg =>
        {
            cfg.For<AppDbContext>().Use<TestAppDbContext>();
        });
    }
}

There’s one “gotcha!” though: at runtime, the “instance” passed to the behavior is guaranteed to implement the ISpecs interface (since it will always be an instance of SpecsFor<T>), but that may not be obvious at compile time.  If our IDatabaseSpecs class did not implement the ISpecs interface itself, then you’d have to cast the instance to access the container, like so:

public interface IDatabaseSpecs
{
    //Stuff
}

public class DatabaseFactory : Behavior<IDatabaseSpecs>
{
    public override void SpecInit(IDatabaseSpecs instance)
    {
        ((ISpecs)instance).MockContainer.Configure(cfg =>
        {
            cfg.For<AppDbContext>().Use<TestAppDbContext>();
        });
    }
}

As usual, please create an issue over at Github if you run into any problems.

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications. He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight, where he publishes courses on everything from web applications to testing!

blog comments powered by Disqus