我是NSubstitue的新手(在.NET中對單元測試頗爲新穎)。我想測試我的課程是否將所有數據保存在不同文件中,例如, StringDictionary。我怎樣才能用NSubstitute僞造當前類的方法?
說我有我的DataManipulation.cs
類:
using System;
using System.Collections;
using System.Collections.Specialized;
namespace ApplicationName
{
// interface for NSubstitute
public interface IManipulator
{
void saveAllData();
void saveEntry(string entryKey, string entryValue);
}
public class DataManipulator : IManipulator
{
protected StringDictionary _data {get; private set;}
public DataManipulator()
{
_data = new StringDictionary();
}
public void addData(string name, string data)
{
this._data.Add(name, data);
}
public void saveAllData()
{
// potential implementation - I want to test this
foreach (DictionaryEntry entry in this._data)
{
this.saveEntry(entry.Key.ToString(), entry.Value.ToString());
}
}
public void saveEntry(string entryKey, string entryValue)
{
// interact with filesystem, save each entry in its own file
}
}
}
我想測試:當我打電話DataManipulator.saveAllData()
它保存在一個單獨的文件中的每個_data
項 - 這意味着它運行saveEntry
的次數等於_data.Count
。 NSubstitute可以嗎?
每次我嘗試使用DataManipulation作爲測試對象,並單獨作爲模擬 - 當我運行Received()
我有信息,沒有進行調用。
NUnit測試模板,我想用:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using NSubstitute;
namespace ApplicationName.UnitTests
{
[TestFixture]
class DataManipulatorTests
{
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
DataManipulator dm = new DataManipulator();
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
// how to assert if it called DataManipulator.saveEntry() three times?
}
}
}
或者我應該做它在不同的方式?
謝謝!很棒 – BartekR 2014-09-20 19:50:34