我有一个如下所示的类方法:
private List<string> DataStoreContents = new List<string>(new[] { "", "", "", "" });
public void InputDataStore(int DataStore, string Data)
{
DataStoreContents[DataStore - 1] = Data;
}我希望确保DataStore是>=1和<= 4
如何编写单元测试来确保这一点?
发布于 2012-02-23 00:47:17
任一
Assert.IsTrue(DataStore >= 1 && DataStore <= 4);或者,如果您更喜欢流畅的界面
Assert.That(DataStore, Is.GreaterThanOrEqualTo(1).And.LessThanOrEqualTo(4));编辑-回应您上面的说明
听起来您想要进行某种屏障检查,以检查提供的值是否在范围内。
在这种情况下,您有几个选择:
菲利普·福里给出了一个涉及代码合同的答案。
另一种简单的方法是自己编写屏障检查:
public void InputDataStore(int DataStore, string Data)
{
if (DataStore < 1 || DataStore > 4)
{
throw new ArgumentOutOfRangeException("DataStore", "Must be in the range 1-4 inc.");
}
DataStoreContents[DataStore - 1] = Data;
}如果您不想抛出异常,但可能想记录它并干净利落地退出:
public void InputDataStore(int DataStore, string Data)
{
if (DataStore < 1 || DataStore > 4)
{
// log something here and then return
return;
}
DataStoreContents[DataStore - 1] = Data;
}以链接回单元测试。例如,单元测试可以是您编写的一个测试,用于检查当使用超出范围的值调用InputDataStore时,它是否抛出了expcetion。另一种可能是,当使用范围内的值调用它时,它不会抛出异常,并且它会正确地更新DataStoreContents。
发布于 2012-02-23 00:42:55
Assert.IsTrue(DataStore >= 1 && DataStore <= 4);发布于 2012-02-23 00:48:54
您还可以使用具有许多其他好处的代码契约,例如静态代码检查。这意味着你将在“代码时间”收到关于不正确使用该方法的警告。
public void InputDataStore(int DataStore, string Data)
{
Contract.Requires(DataStore >= 1 && DataStore <= 4);
DataStoreContents[DataStore - 1] = Data;
}这里有一个很好的阅读:http://devjourney.com/blog/code-contracts-part-1-introduction/
https://stackoverflow.com/questions/9399069
复制相似问题