我是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