单元测试 - 用户控制器的方法
问题描述:
我有一个名为“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);
,但是当我尝试调用通过单位方法这个方法:
[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.");
}
我得到一个错误“引用未设置。 ..“。我知道为什么会发生(_repository为空,因为在我的情况下未调用Initialize方法,但如何正确执行它?
答
如果您希望DBRepository在测试期间从您的后备数据存储区实际执行Get
,改变你的_repository
场是一个Lazy<DBRepository>
,是被第一次使用时初始化。(我假设它是new
在初始化方法编起来,而不是构造函数,因为它依赖于当前请求上下文?)
如果您希望这是一个真正的单元测试,它不应该测试DBRepository类:你应该编程到一个你可以模拟的接口,另外,你需要使它成为你的DBRepository
来自某个地方,它可以由测试用例提供。您可以让它由工厂构建或作为单例提供,并且测试用例可以设置工厂或单例以提前提供模拟对象。但是,最好的方法是使用依赖注入,所以当你构造new UserController()
时,你可以提供一个伪/模拟的IDBRepository。
你能告诉我一个例子吗? – 2013-02-27 01:18:57
@ user285336:不幸的是,这是一个相当庞大的话题,在你的案例中的具体实现将取决于你的系统的细节超出了*问题的范围。我可以建议的最好的事情是花时间研究与单元测试有关的依赖注入和模仿。 – StriplingWarrior 2013-02-28 00:10:22