假设我有两个搜索算法的实现,它们为相同的输入返回相同的结果。它们都实现相同的接口。
我如何使用单个[TestClass]来测试两种实现,而不是创建两个最终具有相同逻辑的测试文件?
我可以告诉MSUnit用不同的构造函数参数启动一个测试两次吗?
也许我应该以某种方式注入它?
发布于 2013-03-25 05:18:34
使用abstract test class
[TestClass]
public abstract class SearchTests
{
private ISearcher _searcherUnderTest;
[TestSetup]
public void Setup()
{
_searcherUnderTest = CreateSearcher();
}
protected abstract ISearcher CreateSearcher();
[TestMethod]
public void Test1(){/*do stuff to _searcherUnderTest*/ }
// more tests...
[TestClass]
public class CoolSearcherTests : SearcherTests
{
protected override ISearcher CreateSearcher()
{
return new CoolSearcher();
}
}
[TestClass]
public class LameSearcherTests : SearcherTests
{
protected override ISearcher CreateSearcher()
{
return new LameSearcher();
}
}
}发布于 2013-03-22 20:39:58
您已经用NUnit标记了您的问题,但您询问的是MSTest。您所询问的内容可以通过NUnit中的参数化测试夹具来实现。我对MSTest还不够熟悉,无法在那里推荐一种等效的方法,快速搜索一下就会发现MSTest可能没有这个特性。
在NUnit中,您可以通过将多个[TestFixture(...)]属性应用于具有不同参数的fixture类来参数化测试夹具。这些参数将被传递给fixture构造函数。
由于可以传递的参数类型有限制,您可能需要在指定算法时传递一个字符串,然后在构造函数中将提供搜索算法的委托或对象分配给测试中使用的成员字段。
例如:
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace MyTests
{
public static class SearchAlgorithms
{
public static int DefaultSearch(int target, IList<int> data)
{
return data.IndexOf(target);
}
public static int BrokenSearch(int target, IList<int> data)
{
return 789;
}
}
[TestFixture("forward")]
[TestFixture("broken")]
public class SearchTests
{
private Func<int, IList<int>, int> searchMethod;
public SearchTests(string algorithmName)
{
if (algorithmName == "forward")
{
this.searchMethod = SearchAlgorithms.DefaultSearch;
return;
}
if (algorithmName == "broken")
{
this.searchMethod = SearchAlgorithms.BrokenSearch;
}
}
[Test]
public void SearchFindsCorrectIndex()
{
Assert.AreEqual(
1, this.searchMethod(2, new List<int> { 1, 2, 3 }));
}
[Test]
public void SearchReturnsMinusOneWhenTargetNotPresent()
{
Assert.AreEqual(
-1, this.searchMethod(4, new List<int> { 1, 2, 3 }));
}
}
}发布于 2013-03-22 19:59:53
我宁愿在一个[TestClass]中有两个不同的[TestMethod],每个[TestClass]只测试一个实现:这样,失败的测试将始终正确地指出哪个实现出错了。
https://stackoverflow.com/questions/15569732
复制相似问题