public
Created

NUnit Action Container magic

  • Download Gist
IConfigurator.cs
C#
1 2 3 4 5
public interface IConfigurator
{
T GetInstance<T>();
void Inject<T>(T instance);
}
INeedToConfigure.cs
C#
1 2 3 4
public interface INeedToConfigure
{
IConfigurator Configurator { set; }
}
SampleTest.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[TestFixture]
[UseContainer]
public class SampleTest : INeedToConfigure
{
public IConfigurator Configurator { set; private get; }
 
[Test]
public void SimpleTestOne()
{
}
[Test]
public void SimpleTestTwo()
{
}
}
UseContainerAttribute.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
AllowMultiple = true)]
public sealed class UseContainerAttribute: Attribute, ITestAction, IConfigurator
{
private IContainer container;
 
public void BeforeTest(TestDetails details)
{
this.container = Root.Container.GetNestedContainer();
INeedToConfigure configure = details.Fixture as INeedToConfigure;
if(configure != null) {
configure.Configurator = this;
}
}
 
public void AfterTest(TestDetails details)
{
this.container.Dispose();
}
 
public ActionTargets Targets
{
get { return ActionTargets.Suite; }
}
 
public void Inject<T>(T instance)
{
this.container.Configure(cfg => cfg.For<T>().Use(instance));
}
 
public T GetInstance<T>()
{
return this.container.GetInstance<T>();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.