jeudi 8 septembre 2016

Mocking out the Data Accessor

I am trying to learn about using Moq with NUnit and IoC.

I have a Logic method (Login) I am trying to test. It take a request object (Which has a username, password and IP Address). If the username and/or password are empty, the logic returns a failed status, and doesn't go to the data access layer.

So I am creating a unit test to test this. (This my my first attempt with mocking...)

 public void NotNull_Returns_True()
        {
            // Arrange
            var request = new LoginRequest { IPAddress = "1.1.1.1", Username = "dummy", Password = "dummy" };
            var response = new LoginResponse { Request = request, Success = true, Message = "", UserID = 1 };

            // Setup the moc data accessor, as we don't want to gop to the concrete one.
            var MockedDataAccess = new Mock<IDataAccess>();

            // Set it's return value
            MockedDataAccess.Setup(x => x.Login(request)).Returns(response);

            // Instantiate the Logic class we're testing, using a Moc data accessor.
            var logic = new BusinessLogic(MockedDataAccess.Object);

            // Act
            var result = logic.Login(new LoginRequest { Password = "dummy", Username = "dummy", IPAddress = "1.1.1.1" });

            // Assert
            Assert.AreEqual(true, result.Success);
        }

This fails on the assert, as 'result' is NULL.

I'm probably doing a lot wrong. For example, I'm not sure why I need to setup the request and response objects at the top,but because all the examples I find are 'string' and 'int' inputs, it seems I can't use It.IsAny...

Could someone assist me understanding here? What am I doing wrong to get NULL as a result in the assert? I step through and the code executes as expected. But the result is null, because I never called the data accessor (It used the mock).

Edit: Ah,

// Set it's return value
            MockedDataAccess.Setup(x => x.Login(It.IsAny<LoginRequest>())).Returns(response);

That resolved the issue. I'm not sure why, so if you can help me understand and refactor this so that it's as an experienced Moq/UnitTester would expect it to look, that would be very useful.

Aucun commentaire:

Enregistrer un commentaire