Discussions

Ask a Question
Back to All

Constructor will be called before calling Given()-method

Hello,

I am using SpecsFor in Version 4.4.0.

My application logic has a constructor and uses a Unity-Container like this:
namespace SpecsFor_Unity
{
public class Program
{
static void Main(string[] args)
{
}

    public Program(object anyParameter, IUnityContainer unityContainer)
    {
        var foo = unityContainer.Resolve<IFoo>();

        if (foo == null)
        {
            throw new ArgumentNullException(nameof(foo));
        }
    }

    public void DoSomething()
    {
    }
}

}

My test class Looks like this:
namespace SpecsFor_Unity_Test
{
public class UnitTest1 : SpecsFor
{
protected override void Given()
{
var unityContainer = new UnityContainer();

        unityContainer.RegisterType<IFoo, Foo>();

        var program = new Program(new object(), unityContainer);
    }

    protected override void When()
    {
        SUT.DoSomething();
    }

    [Test]
    public void then_check_anything()
    {
        
    }
}

}

The problem is:
the ArgumentNullException will be thrown after resolving unity reference, because constructor is called before Given()-method.

I expected that constructor of Program is called within Given()-method.

What am I doing wrong?

Thanks in advance!

Kind regards,
Stefan

Hi Stefan,

Given is called after your SUT has been initialized. If you need to configure the container or set up mocks before your constructor is called, you'll need to override either InitializeClassUnderTest or ConfigureContainer.

This page defines the full lifecycle of a spec: https://specsfor.readme.io/docs/specsfor-lifecycle

Hi Matt,

works fine with InitializeClassUnderTest :)

Thank you for your help and answer!

Best regards,
Stefan

ο»Ώ