Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit DeploymentItem

Tags:

.net

nunit

In MsTest if I need some file from another project for my test, I can specify DeploymentItem attribute. Is there anything similar in NUnit?

like image 684
SiberianGuy Avatar asked Feb 21 '12 13:02

SiberianGuy


1 Answers

You should check out another thread that contrasts the capabilities of NUnit and MSTest.

The accepted answer here is misleading. NUnit does not offer the [DeploymentItem("")] attribute at all which is what @Idsa wanted an equivalent solution for in NUnit.

My guess is that this kind of attribute would violate the scope of NUnit as a "unit" testing framework as requiring an item to be copied to the output before running a test implies it has a dependency on this resource being available.

I'm using a custom attribute to copy over a localdb instance for running "unit" tests against some sizeable test data that I'd rather not generate with code everytime.

Now using the attribute [DeploymentItem("some/project/file")] will copy this resource from file system into the bin again effectively refreshing my source data per test method:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Struct,      AllowMultiple = false,      Inherited = false)] public class DeploymentItem : System.Attribute {     private readonly string _itemPath;     private readonly string _filePath;     private readonly string _binFolderPath;     private readonly string _itemPathInBin;     private readonly DirectoryInfo _environmentDir;     private readonly Uri _itemPathUri;     private readonly Uri _itemPathInBinUri;      public DeploymentItem(string fileProjectRelativePath) {         _filePath = fileProjectRelativePath.Replace("/", @"\");          _environmentDir = new DirectoryInfo(Environment.CurrentDirectory);         _itemPathUri = new Uri(Path.Combine(_environmentDir.Parent.Parent.FullName             , _filePath));          _itemPath = _itemPathUri.LocalPath;         _binFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);          _itemPathInBinUri = new Uri(Path.Combine(_binFolderPath, _filePath));         _itemPathInBin = _itemPathInBinUri.LocalPath;          if (File.Exists(_itemPathInBin)) {             File.Delete(_itemPathInBin);         }          if (File.Exists(_itemPath)) {             File.Copy(_itemPath, _itemPathInBin);         }     } } 

Then we can use like so:

[Test] [DeploymentItem("Data/localdb.mdf")] public void Test_ReturnsTrue()  {     Assert.IsTrue(true); } 
like image 70
Matthew Avatar answered Sep 20 '22 09:09

Matthew