Created
December 19, 2013 13:41
-
-
Save orient-man/8039247 to your computer and use it in GitHub Desktop.
Simplified implementation of xunit's IUseFixture handling for NUnit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using NUnit.Framework; | |
namespace Piatka.Infrastructure.Tests.Fixtures | |
{ | |
public interface IUseFixture<T> where T : IDisposable | |
{ | |
void SetFixture(T data); | |
} | |
public abstract class HasFixtures | |
{ | |
private readonly IList<Type> fixtureTypes; | |
private readonly Stack<IDisposable> fixtures = new Stack<IDisposable>(); | |
protected HasFixtures() | |
{ | |
fixtureTypes = | |
GetType() | |
.GetInterfaces() | |
.Where(o => o.Name == typeof(IUseFixture<>).Name) | |
.Select(o => o.GetGenericArguments()[0]) | |
.ToList(); | |
} | |
[SetUp] | |
public virtual void SetUpEachTest() | |
{ | |
foreach (var type in fixtureTypes) | |
{ | |
// TODO: from IoC | |
var instance = (IDisposable)Activator.CreateInstance(type); | |
fixtures.Push(instance); | |
GetType() | |
.GetMethod("SetFixture", new[] { type }) | |
.Invoke(this, new object[] { instance }); | |
} | |
} | |
[TearDown] | |
public virtual void TearDownEachTest() | |
{ | |
while (fixtures.Count > 0) | |
fixtures.Pop().Dispose(); | |
} | |
} | |
public class FixtureA : IDisposable | |
{ | |
public bool IsDisposed { get; private set; } | |
public void Dispose() | |
{ | |
IsDisposed = true; | |
} | |
} | |
public class FixtureB : IDisposable | |
{ | |
public bool IsDisposed { get; private set; } | |
public void Dispose() | |
{ | |
IsDisposed = true; | |
} | |
} | |
[TestFixture, Category("Unit")] | |
public class SampleTests : HasFixtures, IUseFixture<FixtureA>, IUseFixture<FixtureB> | |
{ | |
private FixtureA a; | |
private FixtureB b; | |
public void SetFixture(FixtureA data) | |
{ | |
a = data; | |
} | |
public void SetFixture(FixtureB data) | |
{ | |
b = data; | |
} | |
public override void SetUpEachTest() | |
{ | |
base.SetUpEachTest(); | |
Assert.That(a.IsDisposed, Is.False); | |
Assert.That(a.IsDisposed, Is.False); | |
} | |
public override void TearDownEachTest() | |
{ | |
base.TearDownEachTest(); | |
Assert.That(a.IsDisposed, Is.True); | |
Assert.That(a.IsDisposed, Is.True); | |
} | |
[Test] | |
public void CanUseBothFixtures_test1() | |
{ | |
Assert.That(a, Is.Not.Null); | |
Assert.That(b, Is.Not.Null); | |
} | |
[Test] | |
public void CanUseBothFixtures_test2() | |
{ | |
Assert.That(a, Is.Not.Null); | |
Assert.That(b, Is.Not.Null); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment