#author("2023-11-14T14:12:16+08:00","default:Admin","Admin")
#author("2023-11-15T13:14:00+08:00","default:Admin","Admin")
[[MSTest]]

&color(red){※前提条件:本情報はMSTestV2を基づいて説明してる};

#contents

* DeploymentItemAttribute [#d05af775]

&color(red){和下面有冲突};

MSTest V2 框架引入了 DeploymentItemAttribute,用于将指定为部署项的文件或文件夹复制到部署目录(无需添加所复制文件在项目文件夹内的 TestResults 文件夹中的自定义输出路径)。 部署目录是所有部署项以及测试项目 DLL 所在的位置。

它既可以用于测试类(标有 TestClass 属性的类),也可以用于测试方法(标有 TestMethod 属性的方法)。

用户可以使用多个属性实例来指定多个项。

可在此处查看其构造函数。

 https://learn.microsoft.com/zh-cn/visualstudio/test/using-microsoft-visualstudio-testtools-unittesting-members-in-unit-tests?view=vs-2022

#codeprettify{{
[TestClass] 
[DeploymentItem(@"C:\classLevelDepItem.xml")]   // Copy file using some absolute path
public class UnitTest1
{
    [TestMethod]
    [DeploymentItem(@"..\..\methodLevelDepItem1.xml")]   // Copy file using a relative path from the dll output location
    [DeploymentItem(@"C:\DataFiles\methodLevelDepItem2.xml", "SampleDataFiles")]   // File will be added under a SampleDataFiles in the deployment directory
    public void TestMethod1()
    {
        string textFromFile = File.ReadAllText("classLevelDepItem.xml");
    }
}
}}

* 问题 [#k183a83f]

.Net Core projects 里面已经不支持 DeploymentItem 了,为了从 MSTest V1 迁移到 V2

* 解决方案 [#kdc4567b]

#codeprettify{{
// Declare this property - this is set by MSTest
public TestContext TestContext { get; set; }

// In test initialization - note the signature should be exactly this
// A static void method with one argument of type TestContext 
[TestInitialize]
public void TestSetup()
{
    var testName = TestContext.TestName;
    var method = new StackFrame().GetMethod().DeclaringType.GetMethod(testName);
    var attributes = method.GetCustomAttributes(typeof(DeploymentItemAttribute)).ToArray();
    foreach(DeploymentItemAttribute att in attributes)
    {
        var origin = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), att.Path);
        var targetDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), att.OutputDirectory);
        // Creates dir for deployment item
        Directory.CreateDirectory(targetDir);
        // Copies item
        try
        {
            File.Copy(origin, targetDir);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Error copying deployment item {0} to {1} message {2}", origin, targetDir, ex.Message);
        }
    }
}
}}

#hr();
コメント:
#comment_kcaptcha

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS