开发者

DynamicMock and Expected #1, Actual #0

开发者 https://www.devze.com 2023-02-21 03:00 出处:网络
I think I don\'t understand something in Mock, if I use a DynamicMock, it should only verify the call that I expect right? Why do I get an exception in my test below? I don\'t want to verify that the

I think I don't understand something in Mock, if I use a DynamicMock, it should only verify the call that I expect right? Why do I get an exception in my test below? I don't want to verify that the Session is set, I only want to verify that the _authService.EmailIsUnique is call with the right params. My problem is that in my AdminController I set _authService.Session...

 private MockRepository _mock;
 private ISession _session;
 private IAuthenticationService _authService;
 private AdminController _controller;
 private TestControllerBuilder _builder;

 [SetUp]
 public void

 Setup()
 {
        _mock = new MockRepository();
        _session = _mock.DynamicMock<ISession>();
        _authService = _mock开发者_Go百科.DynamicMock<IAuthenticationService>();
        _controller = new AdminController(_authService, _session);
        _builder = new TestControllerBuilder();
        _builder.InitializeController(_controller);
 }

 [Test]
 public void Register_Post_AddModelErrorWhenEmailNotUnique()
 {
                var userInfo = new RegisterModel();
                userInfo.Email = "the_email@domain.com";

                //_authService.Expect(x => x.Session = _session).Repeat.Once();
                Expect.Call(_authService.EmailIsUnique(userInfo.Email)).Repeat.Once().Return(false);

                _mock.ReplayAll();
                var result = _controller.Register(userInfo);
                var viewResult = (ViewResult)result;

                _authService.VerifyAllExpectations();
                result.AssertViewRendered().ForView("").WithViewData<RegisterModel>();
                Assert.That(viewResult.ViewData.Model, Is.EqualTo(userInfo));
 }

Rhino.Mocks.Exceptions.ExpectationViolationException : IAuthenticationService.set_Session(ISessionProxy2f2f623898f34cbeacf2385bc9ec641f); Expected #1, Actual #0.

Thanks for the help!

Update

Here's part of my controller and my AuthService... I'm using Ninject as DI, since my AuthService is in my Domain and Ninject is in my WebApp I don't know how I could use DI in my AuthService to resolve my Session. Thanks again!

    public partial class AdminController : Controller
    {
        private IAuthenticationService _authService;
        private ISession _session;

        public AdminController(IAuthenticationService authService, ISession session)
        {
            _authService = authService;
            _authService.Session = session;
            _session = session;
        }
[HttpPost]
        [Authorize(Roles = "Admin")]
        [ValidateAntiForgeryToken]
        public virtual ActionResult Register(RegisterModel userInfo)
        {
            if (!_authService.EmailIsUnique(userInfo.Email)) ModelState.AddModelError("Email", Strings.EmailMustBeUnique);
            if (ModelState.IsValid)
            {
                return RegisterUser(userInfo);
            }

            return View(userInfo);
        }
private RedirectToRouteResult RegisterUser(RegisterModel userInfo)
        {
            _authService.RegisterAdmin(userInfo.Email, userInfo.Password);
            var authToken = _authService.ForceLogin(userInfo.Email);
            SetAuthCookie(userInfo.Email, authToken);
            return RedirectToAction(MVC.Auction.Index());
        }
}

public class AuthenticationService : IAuthenticationService
    {
        public ISession Session { get; set; }

public bool EmailIsUnique(string email)
        {
            var user = Session.Single<User>(u => u.Email == email);
            return user == null;
        }
}


My problem is that in my AdminController I set _authService.Session

Yes this is a problem indeed as this is the responsibility of your DI framework, not your controller code. So unless ISession is directly used by the controller it should be removed from it. The controller shouldn't do any plumbing between the service and any dependencies of this service.

So here's an example:

public class AdminController : Controller
{
    private readonly IAuthenticationService _authService;
    public AdminController(IAuthenticationService authService)
    {
        _authService = authService;
    }

    public ActionResult Register(RegisterModel userInfo)
    {
        if (!_authService.EmailIsUnique(userInfo.Email))
        {
            ModelState.AddModelError("Email", Strings.EmailMustBeUnique);
            return View(userInfo);
        }
        return RedirectToAction("Success");
    }
}

Notice that the admin controller shouldn't rely on any session. It already relies on the IAuthenticationService. The way this service is implemented is not important. And in this case a proper unit test would be:

private IAuthenticationService _authService;
private AdminController _controller;
private TestControllerBuilder _builder;

Setup()
{
    _authService = MockRepository.GenerateStub<IAuthenticationService>();
    _controller = new AdminController(_authService);
    _builder = new TestControllerBuilder();
    _builder.InitializeController(_controller);
}

[Test]
public void Register_Post_AddModelErrorWhenEmailNotUnique()
{
    // arrange
    var userInfo = new RegisterModel();
    userInfo.Email = "the_email@domain.com";
    _authService
        .Stub(x => x.EmailIsUnique(userInfo.Email))
        .Return(false);

    // act
    var actual = _controller.Register(userInfo);

    // assert
    actual
        .AssertViewRendered()
        .WithViewData<RegisterModel>()
        .ShouldEqual(userInfo, "");
    Assert.IsFalse(_controller.ModelState.IsValid);
}

UPDATE:

Now that you have shown your code I confirm:

Remove the ISession dependency from your controller as it is not needed and leave this job to the DI framework.

Now I can see that your AuthenticationService has a strong dependency on ISession, so constructor injection would be more adapted instead property injection. Use property injection only for optional dependencies:

public class AuthenticationService : IAuthenticationService
{
    private readonly ISession _session;
    public AuthenticationService(ISession session)
    {
        _session = session;
    }

    public bool EmailIsUnique(string email)
    {
        var user = _session.Single<User>(u => u.Email == email);
        return user == null;
    }
}

and the last part that is left is the plumbing. This is done in the ASP.NET MVC application which has references to all other layers. And because you have mentioned Ninject you could install the Ninject.MVC3 NuGet and in the generated ~/App_Start/NinjectMVC3 simply configure the kernel:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ISession>().To<SessionImpl>();
    kernel.Bind<IAuthenticationService>().To<AuthenticationService>();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号