2011-11-10 15 views
8

我知道我可以使用文件中的數據驅動單元測試,例如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() {} 
+0

類似問題[如何使用MSTest進行RowTest?](http://stackoverflow.com/q/347535) –

回答

1

一個簡單的解決方案可以是這樣......

private void TestData(IEnumerable what) { ... your test method ... } 

[TestMethod] 
public void TestDataInMemory() { List<T> mylist = ...; this.TestData(mylist); } 

[TestMethod] 
[DataSource(
    "Microsoft.VisualStudio.TestTools.DataSource.CSV", 
    "Data.csv", 
    "Data#csv", 
    DataAccessMethod.Sequential)] 
public void TestData() { this.TestData(testContextInstance ...) } 

這樣你既可以從文件加載數據,並與來自加載的數據使用的測試方法記憶。

+0

感謝您的建議。不幸的是,在我看來,TestDataInMemory()測試將僅針對任意數量的數據條目運行一次,而TestData()測試將針對每個條目運行一次。爲了我的目的,我寧願爲每個條目運行一次測試。 –

1

我不認爲你可以通過[DataSource]屬性來做到這一點,但你可以手動完成相同的事情。

將數據加載到使用[AssemblyInitialize][ClassInitialize]修飾的方法中。然後重寫你的測試來循環數據。不幸的是,這種方式最終只會得到一次測試,而不是每次測試的單獨結果。

+0

是的,數據已經在[ClassInitialize]函數中設置,我嘗試了你的建議。它確實有效,但對所有數據進行單個測試意味着斷言將在第一次失敗的測試中停止該功能。不是我真正想要的。感謝您的建議。 –

3

如果它在內存中,我的首選是不使用DataSource,而是使用T4模板自動生成單元測試。這樣,您只會編寫一次測試,但在測試運行的結果中,您會看到每個測試輸入的條目。將這個.tt文件添加到您的測試項目中。

<#@ template debug="false" hostspecific="true" language="C#v3.5" #> 
<#@ assembly name="System.Core.dll" #> 
<#@ assembly name="System.Data.dll" #> 
<#@ import namespace="System.Collections.Generic" #> 
<#@ import namespace="System.Linq" #> 
<#@ output extension=".cs" #> 
<# 
     List<string> DataList = AccessInMemoryData(); 
#> 
using System; 
using System.Text; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 

namespace TestProject1 
{ 
[TestClass] 
public class UnitTest1 
{ 
    <# foreach (string currentTestString in DataList) { #> 
    [TestMethod] 
    public void TestingString_<#= currentTestString #> 
    { 
    string currentTestString = "<#= currentTestString #>"; 
    // TODO: Put your standard test code here which will use the string you created above 
    } 
    <# } #> 
} 
} 
+0

這是一個整潔的想法。 –

+0

認真愛這個方法的人! –

1

answered a similar question和我以前使用的解決方案是從我的內存數據生成一個簡單的CSV文件。

相關問題