Primi test dell'unità!MVC ASP.NET con repository che causa errori
-
15-11-2019 - |
Domanda
Sono molto nuovo per il test unitario, quindi sto iniziando per il mio primo set di test oggi.Sto usando la biblioteca JustMock
da Telerik.Sebbene qualsiasi informazione di test dell'unità sia buona.Sto avendo un po 'problemi con un servizio di interfaccia che passa attraverso il mio metodo.Di seguito è riportato il mio metodo MembershipController.Register(model)
...
[CaptchaValidator]
[HttpPost]
public ActionResult Register(Models.Membership.Registration model)
{
// just for good mesure, truncate any spaces that are given
System.Text.RegularExpressions.Regex.Replace(model.Email, @"\s", "");
if (ModelState.IsValid)
{
// Attempt to register the User and return any applicable status that has to do
// with the result.
var createStatus = membershipService.RegisterMember(model.Email, model.Password);
// if the member is able to be created successfully, log them in now and begin the
// authentication portion of the registration, otherwise, display the registration
// errors and return to the view.
if (createStatus == Membership.MemberCreateStatus.Success)
{
formsAuthentication.SignIn(model.Email, false /* createPersistentCookie */);
return RedirectToAction("Success");
}
else
{
ModelState.AddModelError("", Membership.Validator.ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
.
Ed ecco il test misero che sto cercando di correre ...
[TestMethod]
public void Register_Post_ReturnsRedirectOnSuccess()
{
// Arrange
var controller = Mock.Create<Web.Controllers.MembershipController>();
var repository = Mock.Create<Membership.IMembershipService>();
Mock.Arrange(() => repository.RegisterMember("acceptible@email.com", "acceptiblePassword")).Returns(Membership.MemberCreateStatus.Success);
// Model
var model = new Web.Models.Membership.Registration
{
Email = "acceptible@email.com",
Password = "acceptiblePassword",
ConfirmPassword = "acceptiblePassword"
};
// Act
var result = controller.Register(model);
// Assert
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
}
.
Il test non riesce perché membershipService
si risolve come NULL.Non sono sicuro di cosa fare qui.Questa è la mia prima scorta nell'aspetto dell'unità Test di ASP.NET MVC.Qualcuno può darmi qualche consiglio?
Sto usando Ninject
per iniettare IMembershipService
attraverso il costruttore.È implementato dalla classe MembershipService
.Il codice funziona bene quando lo eseguo, ma i test dell'unità non riescono.
Soluzione
I don't see you passing repository anywhere into your controller. Normally you would have IMembershipService as a parameter in your controller's constructor that you can then pass in when needed or use MVC's Service Locator to grab the Ninject instance and pass it in.
:)