有没有办法使用内存中已有的数据来驱动单元测试?
我知道我可以使用文件中的数据来驱动单元测试,例如 csv 或 xml 文件中的数据。
例如:
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.CSV",
"Data.csv",
"Data#csv",
DataAccessMethod.Sequential)]
public void TestData() {}
我想知道是否有一种方法可以使用内存中已有的数据结构来驱动测试,而不是使用文件。
像这样的东西:
// this structure has the data to use in the unit test
var DataList = new List<string>();
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.IEnumerable",
"DataList",
"DataList",
DataAccessMethod.Sequential)]
public void TestData() {}
I know I can use data in files to drive unit test, for example data inside a csv or xml file.
For example:
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.CSV",
"Data.csv",
"Data#csv",
DataAccessMethod.Sequential)]
public void TestData() {}
I would like to know if there is a way that, instead of using a file, I can use a data structure that's already in memory to drive the tests.
Something like:
// this structure has the data to use in the unit test
var DataList = new List<string>();
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.IEnumerable",
"DataList",
"DataList",
DataAccessMethod.Sequential)]
public void TestData() {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果它在内存中,我的偏好是不使用 DataSource,而是使用 T4 模板自动生成单元测试。这样,您只需编写一次测试,但在测试运行的结果中,您将看到您测试的每个输入的条目。将此 .tt 文件添加到您的测试项目中。
If it's in memory, my preference would be to not use DataSource, but use a T4 template to auto generate your unit tests instead. This way, you will only write the test once, but in the results for the test run, you will see an entry for each of the input you tested. Add this .tt file to your test project.
一个简单的解决方案可以是这样......
通过这种方式,您可以使用测试方法来处理从文件加载的数据和从内存加载的数据。
A simple solution can be this...
In this way you can use your test method both with data loaded from file and with data loaded from memory.
我认为您不能使用
[DataSource]
属性来做到这一点,但您可以手动执行或多或少相同的操作。在用
[AssemblyInitialize]
或[ClassInitialize]
修饰的方法中加载数据。然后重写您的测试以循环数据。不幸的是,这样您最终将得到一个测试,而不是每次测试运行的单独结果。I don't think you can do that with the
[DataSource]
attribute, but you can do a more or less the same thing manually.Load your data in a method decorated with
[AssemblyInitialize]
or[ClassInitialize]
. Then rewrite your tests to loop over the data. Unfortunately this way you will end up with a single test instead of separate results per test run.我回答了类似的问题和我之前使用过的解决方案是从内存数据生成一个简单的 CSV 文件。
I answered a similar question and the solution I have used before is to generate a simple CSV file from my in memory data.
您可以通过 NuGet 使用 MSTestHacks 从 IEnumerable 提供数据,请参阅 这个答案。
You can use MSTestHacks via NuGet to feed data from an IEnumerable, see this answer.
我认为 Gallio Ambience 应该可以解决这个问题。我不确定该项目目前的状况如何。
I think Gallio Ambience was supposed to solve this problem. I'm not sure what the state of the project is, currently.