【发布时间】:2022-09-29 21:27:35
【问题描述】:
我有一个带有控制器的 ASP.NET MVC 4 项目,该控制器调用外部 WCF 以在 VerifyAccount 方法上验证用户登录。这个外部 WCF 将一个 AuthModelUserVerification 类返回给控制器并创建一个包含用户 ID 的 Session:
[HttpPost]
public ActionResult VerifyAccount(string username, string password) {
AuthModelUserVerification result = lms_client.VerifyAccount(username, password);
if (!result.isAuthenticated)
return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
Session[\"SID\"] = result.userid;
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
下面是来自 WCF 的 AuthModelUserVerification 的结构:
public class AuthModel
{
public class UserVerification {
public int? userid { get; set; }
public bool isAuthenticated { get; set; }
public UserVerification()
{
userid = null;
isAuthenticated = false;
}
}
}
我正在尝试对VerifyAccount 方法进行单元测试,以测试在某些条件下返回给浏览器的状态代码。我在用MSTest (.NET)和假装很容易模拟框架。问题在于在Session[\"SID\"] 上设置值
Session[\"SID\"] = result.userid;
调试测试时,我在此行收到以下错误:
你调用的对象是空的
在调试测试时,每次我将鼠标悬停在
Session[\"SID\"]上时,它都会显示为空,但result.userid显示它的值为1因为我通过调用我制作的模拟服务将值传递给它。请在此处查看我的测试的实现:private readonly AuthController _controller_Auth; private readonly ILMS_Service _lms_service; public Auth_UnitTest() { _lms_service = A.Fake<ILMS_Service>(); _controller_Auth = new AuthController(_lms_service); } [TestMethod] public void VerifyAccount_Success() { //Arrange string username = \"admin\"; string password = \"sampleP@sswoRd\"; int userID = 1; int expected_response_code = 200; var session = A.Fake<HttpSessionStateBase>(); A.CallTo(() => session[\"SID\"]).Returns(userID); A.CallTo(() => _lms_service.VerifyAccount(username, password)) .Returns(new AuthModelUserVerification { userid = userID, isAuthenticated = true }); //Act var result = _controller_Auth.VerifyAccount(username, password) as HttpStatusCodeResult; //Assert Assert.AreEqual(expected_response_code, result.StatusCode); }该模拟正在工作,因为当我调试它时,
isAuthenticated的值是true。是Session不起作用。即使制作一个假的HttpSessionStateBase也不能解决问题。我是单元测试的新手,我仍在探索事物,任何帮助将不胜感激。谢谢!
标签: c# asp.net-mvc unit-testing mstest fakeiteasy