1 回答
TA贡献1880条经验 获得超4个赞
实现此目的的常用方法是在您正在测试的对象的构造函数中注入日期/时间提供程序。例如:
public interface IDateTimeProvider
{
DateTime Now();
}
以及该接口的具体实现:
public class DateTimeProvider : IDateTimeProvider
{
public DateTime Now()
{
return Datetime.Now;
}
}
您需要添加IDateTimeProvider到 DI 容器中,
就像是
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
但这取决于你如何设置它,你正在使用哪个框架等。
您的控制器将更改为如下所示:
[Route ("api/[controller]")]
public class DayTodayController : Controller
{
private readonly IDateTimeProvider _dateTimeProvider;
public DayTodayController(IDateTimeProvider dateTimeProvider)
{
_dateTimeProvider = dateTimeProvider;
}
[HttpGet, Route ("GetDate")]
public string GetDate () {
var dateTime = _dateTimeProvider.Now();
var info = $"Today is {dateTime.ToString("dddd, dd MMMM yyyy")} and the time is {dateTime.ToString("hh:mm tt")}";
return info;
}
}
请注意将日期时间分配给变量。多次调用DateTime.Now将给出不同的值,因此您需要对一个实例进行操作以获得所需的行为。
现在您可以使用该接口的非脆弱模拟实现进行测试:
public class DayTodayTests
{
[Test]
public void ReturnsDateAndTime()
{
//Arrange
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
mockedDateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2019, 8, 27, 10, 0, 0));
var controller = new DayTodayController(mockedDateTimeProvider.Object);
//Act
string result = controller.GetDate();
//Assert
string expected = "Today is Tuesday 27 August 2019 and the time is 10:00 AM";
Assert.AreEqual(expected, result);
}
}
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报