【发布时间】:2016-12-06 07:53:30
【问题描述】:
这是我的代码
public class AssistanceRequest : DocumentBase
{
public AssistanceRequest()
{
RequestTime = DateTime.Now;
ExcecutionTime = DateTime.MaxValue;
}
public AssistanceRequest(int amount, string description, DateTime? requestTime) : this()
{
//Check for basic validations
if (amount <= 0)
throw new Exception("Amount is not Valid");
this.Amount = amount;
this.Description = description;
this.RequestTime = requestTime ?? DateTime.Now;
}
private long Amount { get; set; }
private DateTime requestTime { get; set; }
public DateTime RequestTime
{
get { return requestTime; }
set
{
if (value != null && value < DateTime.Now)
throw new Exception("Request Time is not Allowed");
requestTime = value;
}
}
如您所见,我的 Set 正文中有一个验证。我需要测试它。 我尝试在我的测试中调用构造函数。但是在断言之前我在构造函数( act )中得到了异常。如何让我的测试正确?
这是我的测试:
[Theory]
[MemberData("RequestFakeData")]
public void Should_Throw_Exception_RequestDate(int amount, string description, DateTime requestDate)
{
var manager = new AssistanceRequest(amount,description,requestDate);
manager.Invoking(x => x.SomeMethodToChangeRequestTime).ShouldThrowExactly<Exception>()
}
public static IEnumerable<object[]> RequestFakeData
{
get
{
// Or this could read from a file. :)
return new[]
{
new object[] { 0,string.Empty,DateTime.Now.AddDays(1) },
new object[] { 2,"",DateTime.Now.AddDays(-2) },
new object[] { -1,string.Empty,DateTime.Now.AddDays(-3) },
};
}
}
我在这条线上得到了错误:
var manager = new AssistanceRequest(amount,description,requestDate);
构造函数正在尝试设置属性以获取异常。并且没有到达断言。
我的问题是:如何在不更改构造函数的情况下进行测试?
【问题讨论】:
标签: c# asp.net-mvc unit-testing theory xunit