Constructor will be called before calling Given()-method

Posted in General by Stefan Petry Mon Mar 21 2016 12:18:31 GMT+0000 (Coordinated Universal Time)·2·Viewed 1,485 times

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<Program> { 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
Mar 21, 2016

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:

Mar 21, 2016

Hi Matt,

works fine with InitializeClassUnderTest :)

Thank you for your help and answer!

Best regards,

Markdown is allowed