我是編寫單元測試用例的新手。我在User.Identity
上遇到錯誤。我看到嘲笑是解決這個問題的方法,我嘗試了一些不適合我的案例。我已經加入我的代碼關於用戶身份的空引用
我的控制器
public ActionResult CreateStage (EnthiranStageViewModel enthiranStage)
{
if (ModelState.IsValid)
{
Stage stage = enthiran.Insert_Stage(enthiranStage);
//logging Stage Creation
util.ApplicationLog(new ViewModel.Logs.ApplicationLogViewModel
{
GameCategorys = GameCategory.Enthiran,
Event = Events.EnthiranStageCreation,
SessionAttemptId = null,
UserId = User.Identity.GetUserId<int>(),
OptionalParameter1 = enthiranStage.GameId,
OptionalParameter2 = stage.Id,
Description = "Enthiran stage created"
});
return RedirectToAction("Stages", new
{
id = stage.GameId
});
}
return View();
}
以下是我測試的情況下
[TestMethod()]
public void createStage ()
{
EnthiranStageViewModel enthiranStage = new EnthiranStageViewModel
{
StageType=0,
TriggerBeginType = Akton.Areas.Challenge.Models.TriggerType.Manual,
TriggerEndType= Akton.Areas.Challenge.Models.TriggerType.Manual,
TimeLimit = new TimeSpan(9, 6, 13),
TriggerBeginTime= new DateTime(2016, 09, 3, 9, 6, 13),
TriggerEndTime= new DateTime(2016, 09, 3, 9, 6, 13),
StartValueType= Akton.Areas.Challenge.Models.StartValueType.Global,
StageDate= new DateTime(2016, 09, 3, 9, 6, 13),
Proforma=25,
GameId=19,
CreatedTime=new DateTime(2016, 09, 3, 9, 6, 13),
UpdatedTime= new DateTime(2016, 09, 3, 9, 6, 13),
StageName="Test",
};
EnthiranController controller = new EnthiranController();
JsonResult actual = controller.CreateStage(enthiranStage) as JsonResult;
var result = actual.Data;
Assert.AreEqual("{ success = True }", result.ToString());
}
在這裏,我必須通過userId
在ViewModel.Logs.ApplicationLogViewModel
,我不知道該怎麼做。
我該如何得到applicationLogViewModel
的userId
?
檢查https://stackoverflow.com/questions/40230776/how-to-mock-httpcontext-user/40234602#40234602 – Nkosi
檢查http://stackoverflow.com/a/39453132/5233410 – Nkosi
你應該還要注意被測方法可以返回一個視圖結果或者重定向到操作結果,但是單元測試正在檢查JSON結果。這將導致'actual'變量爲'null' – Nkosi