C# 单元测试mvc登录
我一直在创建一个单元测试,但似乎失败了。有人能帮我为这个控制器创建一个单元测试吗 我已经试过各种方法了C# 单元测试mvc登录,c#,asp.net-mvc,unit-testing,model-view-controller,login,C#,Asp.net Mvc,Unit Testing,Model View Controller,Login,我一直在创建一个单元测试,但似乎失败了。有人能帮我为这个控制器创建一个单元测试吗 我已经试过各种方法了 public class logInController : Controller { [HttpPost] public ActionResult Index(logInModel model) { if(ModelState.IsValid) {
public class logInController : Controller
{
[HttpPost]
public ActionResult Index(logInModel model)
{
if(ModelState.IsValid)
{
int match = 0;
sqlConn = new SqlConnection(sqlConnString);
sqlComm = new SqlCommand("spLogin", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.AddWithValue("@userName", model.Username);
sqlComm.Parameters.AddWithValue("@password", model.Password);
SqlParameter userMatch = new SqlParameter("@userMatch", SqlDbType.Int);
userMatch.Direction = ParameterDirection.Output;
sqlComm.Parameters.Add(userMatch);
sqlConn.Open();
sqlComm.ExecuteNonQuery();
match = Convert.ToInt32(sqlComm.Parameters["@userMatch"].Value);
sqlConn.Close();
if (match != 0)
{
FormsAuthentication.SetAuthCookie(model.Username, false);
return RedirectToAction("index","home");
}
else
ModelState.AddModelError("", "Invalid username or password");
}
return View();
}
}
现在我正在试这个
public void LoginTest()
{
var controller = new logInController();
var loginmodel = new logInModel
{
Username = "arwinortiz",
Password = "123456"
};
FormsAuthentication.SetAuthCookie(loginmodel.Username, false);
var result = (RedirectToRouteResult)controller.Index(loginmodel);
result.RouteValues["action"].Equals("index");
result.RouteValues["controller"].Equals("home");
Assert.AreEqual("index", result.RouteValues["action"]);
Assert.AreEqual("home", result.RouteValues["controller"]);
}
首先,您需要将数据库和表单身份验证调用抽象到它们自己的关注点/接口中,以便对它们进行模拟。(羞耻……羞耻……) 完成后,您的控制器可以重构为
public class logInController : Controller {
private IAuthenticationService authenticator;
private IFormsAuthenticationService formsAuthentication;
public MvcTestsController(IAuthenticationService userAuthentication, IFormsAuthenticationService formsAuthentication) {
this.authenticator = userAuthentication;
this.formsAuthentication = formsAuthentication;
}
[HttpPost]
public ActionResult Index(logInModel model) {
if (ModelState.IsValid) {
bool match = authenticator.Authenticate(model.Username, model.Password);
if (match) {
formsAuthentication.SetAuthCookie(model.Username, false);
return RedirectToAction("index", "home");
} else
ModelState.AddModelError("", "Invalid username or password");
}
return View();
}
}
接下来,我们编写登录的单元测试
注意:我用于模拟依赖项和断言结果
[TestMethod]
public void LoginTest() {
//Arrange
var loginmodel = new logInModel {
Username = "arwinortiz",
Password = "123456"
};
var mockAuthenticator = new Mock<IAuthenticationService>();
mockAuthenticator
.Setup(x => x.Authenticate(It.Is<string>(s => s == loginmodel.Username), It.Is<string>(s => s == loginmodel.Password)))
.Returns(true);
var mockFormsAuthentication = new Mock<IFormsAuthenticationService>();
bool isAuthCookieSet = false;
mockFormsAuthentication
.Setup(x => x.SetAuthCookie(It.Is<string>(s => s == loginmodel.Username), It.IsAny<bool>()))
.Callback(() => { isAuthCookieSet = true; });
var controller = new logInController(mockAuthenticator.Object, mockFormsAuthentication.Object);
//Act
var result = (System.Web.Mvc.RedirectToRouteResult)controller.Index(loginmodel);
//Assert (using FluentAssertions)
result.Should().NotBeNull(because: "the result should have redirected for entered user ");
result.RouteValues["action"].ShouldBeEquivalentTo("index", because: "the redirection was to home.index action");
result.RouteValues["controller"].ShouldBeEquivalentTo("home", because: "the result should redirect to home controller");
isAuthCookieSet.Should().BeTrue(because: "auth cookie is set if the user was authenticated");
}
[TestMethod]
公共无效登录测试(){
//安排
var loginmodel=新loginmodel{
Username=“arwinortiz”,
密码=“123456”
};
var mockAuthenticator=new Mock();
模拟验证器
.Setup(x=>x.Authenticate(It.Is(s=>s==loginmodel.Username),It.Is(s=>s==loginmodel.Password)))
.返回(真);
var mockFormsAuthentication=new Mock();
bool-isAuthCookieSet=false;
模拟形式认证
.Setup(x=>x.SetAuthCookie(It.Is(s=>s==loginmodel.Username),It.IsAny())
.Callback(()=>{isAuthCookieSet=true;});
var控制器=新登录控制器(mockAuthenticator.Object、mockFormsAuthentication.Object);
//表演
var result=(System.Web.Mvc.RedirectToRouteResult)controller.Index(loginmodel);
//断言(使用FluentAssertions)
result.Should().NotBeNull(因为:“结果应该为输入的用户重定向”);
result.RouteValues[“action”]应与“index”等效,因为:“重定向到home.index action”);
result.RouteValues[“controller”]应与“home”等效,因为:“结果应重定向到home controller”);
isAuthCookieSet.Should().BeTrue(因为:“如果用户经过身份验证,则设置了身份验证cookie”);
}
向我们展示您的尝试,我们不会为您构建整个模型。您需要从控制器中提取db内容。只是说。。。
[TestMethod]
public void LoginTest() {
//Arrange
var loginmodel = new logInModel {
Username = "arwinortiz",
Password = "123456"
};
var mockAuthenticator = new Mock<IAuthenticationService>();
mockAuthenticator
.Setup(x => x.Authenticate(It.Is<string>(s => s == loginmodel.Username), It.Is<string>(s => s == loginmodel.Password)))
.Returns(true);
var mockFormsAuthentication = new Mock<IFormsAuthenticationService>();
bool isAuthCookieSet = false;
mockFormsAuthentication
.Setup(x => x.SetAuthCookie(It.Is<string>(s => s == loginmodel.Username), It.IsAny<bool>()))
.Callback(() => { isAuthCookieSet = true; });
var controller = new logInController(mockAuthenticator.Object, mockFormsAuthentication.Object);
//Act
var result = (System.Web.Mvc.RedirectToRouteResult)controller.Index(loginmodel);
//Assert (using FluentAssertions)
result.Should().NotBeNull(because: "the result should have redirected for entered user ");
result.RouteValues["action"].ShouldBeEquivalentTo("index", because: "the redirection was to home.index action");
result.RouteValues["controller"].ShouldBeEquivalentTo("home", because: "the result should redirect to home controller");
isAuthCookieSet.Should().BeTrue(because: "auth cookie is set if the user was authenticated");
}