NUnit DeploymentItem

后端 未结 5 1947
暗喜
暗喜 2020-12-28 15:08

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

5条回答
  •  执念已碎
    2020-12-28 15:29

    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);
    }
    

提交回复
热议问题