我有 MSTest [TestClass] 类,其中包含 15 个测试方法 [TestMethod]。测试类测试“本地”和“远程”存储。使用 Visual Studio22 的 TestExplorer,我想分别查看“LocalStorage”测试和“RemoteStorage”测试。
每个实例都应该有两个参数:StorageType 和 DefaultFolder,它们是根据存储类型设置的
我怎样才能做到这一点?
AFAIK,最佳做法是制作 2 个 TestClass,一个用于本地,一个用于远程。
通过这样做,您会自动单独获得结果。
你永远不应该让 TestMethods 测试不止一件事。
用测试方法创建一个基类。不要将其标记为
TestClass
。然后继承标记为TestClass
的类,这些类在控制行为的初始化方法中设置基类的属性。
// base class with test methods
public class BaseStorageTest
{
protected string defaultFolder;
protected bool remoteStorage;
[TestMethod]
public void TestMethod1()
{
if (remoteStorage)
{
Assert.Fail("Failing remote");
}
}
[TestMethod]
public void TestMethod2()
{
}
[TestMethod]
public void TestMethod3()
{
}
}
// Initialize for local test
[TestClass]
public class LocalStorageTest : BaseStorageTest
{
[TestInitialize]
public void Initialize()
{
remoteStorage = false;
defaultFolder = "....";
}
}
// Initialize for remote test
[TestClass]
public class RemoteStorageTest : BaseStorageTest
{
[TestInitialize]
public void Initialize()
{
remoteStorage = true;
defaultFolder = "....";
}
}
我首先误解了这个问题。这个答案涉及在同一个类中对多个方法进行分组。有关实际问题,请参阅我的其他答案。
TestCategory
属性。
[TestClass]
public class UnitTest1
{
[TestMethod]
[TestCategory("Local")]
public void TestMethod1()
{
}
[TestMethod]
[TestCategory("Local")]
public void TestMethod2()
{
}
[TestMethod]
[TestCategory("Remote")]
public void TestMethod3()
{
}
}
然后在 Test Explorer 窗口中,选择“Group by > Traits”。
我同意@RatzMouze 创建两个测试类但是如果你决定坚持使用一个测试类TestCategory 可以用枚举而不是字符串来完成,如果类别名称改变你需要改变它们全部搜索和替换。
使用 emum
public enum Trait
{
Local,
Remote
}
用法
[TestClass]
public class UnitTest1
{
[TestMethod, TestCategory(nameof(Trait.Local))]
public void TestMethod1()
{
}
[TestMethod, TestCategory(nameof(Trait.Remote))]
public void TestMethod2()
{
}
}
另见测试特征