如何在没有接口实现的情况下编写单元测试
本文关键字:情况下 单元测试 实现 接口 | 更新日期: 2024-10-21 05:47:02
我是单元测试的新手。
我必须在以下代码中测试RefreshAmount
:
private readonly int id;
private readonly IService service;
public MyClass(int id, IService service)
{
this.id= id;
this.service= service;
}
public double Number { get; private set; }
public void RefreshAmount()
{
Number= service.GetTotalSum(id);
}
为RefreshAmount
编写的正确单元测试是什么?
您需要mockIService
。有各种框架可以帮助你实现自动化(比如Moq),但这里有一个简单的例子:
public class MockService : IService
{
public double GetTotalSum(int id)
{
return 10;
}
}
基本上,mock实现了您的接口,但只返回硬编码(或众所周知的)数据。这样就很容易知道你的期望值应该是多少!现在你可以用它来做你的测试:
public void TestMethod()
{
MyClass testObj = new MyClass(1, new MockService());
testObj.RefreshAmount();
Assert.Equals(10, testObj.Number);
}
首先开始简单的尝试"阳光灿烂的一天"或"幸福之路"。。。
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var service = new MyService();
int SomeProperInteger = GetNextInteger();
double SomeProperAmount = .50;
var actual = service.GetTotalSum(SomeProperInteger);
double expected = SomeProperInteger * SomeProperAmount;
Assert.IsTrue(expected = actual, "Test Failed, Expected amount was incorrect.");
}
private int GetNextInteger()
{
throw new System.NotImplementedException();
}
}
从测试将在生产中使用的服务对象开始,如上所示。您必须查看代码以了解GetTotalSum应该做什么,或者查看规范。一旦"快乐路径"起作用,您将使用边界一次最多更改一个参数。在上面的代码中,边界来自GetNextInteger或适当值的列表。您必须编写代码来预测要进行比较的预期值。
在验证服务按设计工作后,使用相同的技术转到使用服务的类。