【发布时间】:2014-11-14 13:52:42
【问题描述】:
我是 NSubstitue 的新手(对 .NET 中的单元测试也很陌生)。我想测试我的班级是否为每个条目将所有数据保存在不同的文件中,例如字符串字典。
假设我有我的课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?
}
}
}
或者我应该以不同的方式来做吗?
【问题讨论】:
标签: c# unit-testing nunit nsubstitute