Skip to content

Instantly share code, notes, and snippets.

@markusrt
Last active December 25, 2015 20:49
Show Gist options
  • Save markusrt/7037965 to your computer and use it in GitHub Desktop.
Save markusrt/7037965 to your computer and use it in GitHub Desktop.
This Gist demonstrates how to use NUnits Action Attributes in order to create and delete a temporary directory on test case level.
[TestFixture]
public class ActionAttributeDemoTest : ITempDirectoryTest
{
public string TemporaryDirectoryToStoreTestData { get; set; }
[Test]
public void ITempDirectoryTest_ImplementsInterface_TemporaryDirectoryIsCreatedAutomatically()
{
Assert.That(Directory.Exists(TemporaryDirectoryToStoreTestData), Is.True);
}
}
/// <summary>
/// Attaching this interface to a NUnit test class provides access
/// to a temporary directory. The directory is created and deleted
/// automatically for each test case.
/// </summary>
[TempDirectoryAwareAction]
public interface ITempDirectoryTest
{
string TemporaryDirectoryToStoreTestData { get; set; }
}
using System.IO;
using NUnit.Framework;
namespace SentryIntegration.TestCommon.NUnit.Actions
{
public class TempDirectoryAwareActionAttribute : TestActionAttribute
{
private DirectoryInfo tempDirectoryToStoreTestData;
public override ActionTargets Targets
{
get { return ActionTargets.Test; }
}
public override void BeforeTest(TestDetails details)
{
var tempDirectoryTest = details.Fixture as ITempDirectoryTest;
if (tempDirectoryTest == null)
{
return;
}
CreateTemporaryDirectoryAndAssignToTest(tempDirectoryTest);
}
public override void AfterTest(TestDetails testDetails)
{
if (tempDirectoryToStoreTestData != null)
{
tempDirectoryToStoreTestData.Delete(true);
}
}
private void CreateTemporaryDirectoryAndAssignToTest(ITempDirectoryTest tempDirectoryTest)
{
tempDirectoryToStoreTestData = CreateTemporaryDirectory();
tempDirectoryTest.TemporaryDirectoryToStoreTestData = tempDirectoryToStoreTestData.FullName;
}
private static DirectoryInfo CreateTemporaryDirectory()
{
var tempFile = Path.GetTempFileName();
File.Delete(tempFile);
return Directory.CreateDirectory(tempFile);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment