我有一个名为"UserController"的控制器,方法名为"Invite"。我的控制器有以下超控方法:
DBRepository _repository;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
_repository = new DBRepository();
}
因此,每次创建UserController类时都会调用此方法。
我的方法"邀请"有以下几行:
var startTime = _repository.Get<AllowedTime>(p => p.TimeID == selectTimeStart.Value);
但是当我试图通过Unit方法调用这个方法时:
[TestMethod()]
[UrlToTest("http://localhost:6001/")]
public void InviteTest()
{
UserController target = new UserController(); // TODO: Initialize to an appropriate value
int? selectTimeStart = 57;
int? selectTimeEnd = 61;
Nullable<int> selectAttachToMeeting = new Nullable<int>(); // TODO: Initialize to an appropriate value
int InvitedUserID = 9; // TODO: Initialize to an appropriate value
UserInviteModel model = new UserInviteModel();
model.Comment = "BLA_BLA_BLA";
ActionResult expected = null; // TODO: Initialize to an appropriate value
ActionResult actual;
actual = target.Invite(selectTimeStart, selectTimeEnd, selectAttachToMeeting, InvitedUserID, model);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
我收到一个错误"Reference is not set…"。我理解为什么会发生这种情况(_repository为null,因为在我的情况下没有调用Initialize方法,但如何正确执行?
如果您希望DBRepository在测试期间实际从备份数据存储中执行Get
,则可以将_repository
字段更改为Lazy<DBRepository>
,该字段在首次使用时初始化。(我假设它是在Initialize方法中new
,而不是在构造函数中,因为它依赖于当前的请求上下文?(
如果您希望这是一个真正的单元测试,那么它根本不应该测试DBRepository类:您应该对一个可以模拟的接口进行编程。此外,您需要使DBRepository
来自测试用例可以提供它的地方。您可以让工厂构建它或将其作为单例提供,测试用例可以设置工厂或单例提前提供模拟对象。然而,最好的方法是使用依赖注入,因此在构造new UserController()
时可以提供一个假的/模拟IDBRepository。