moq, how to test the save method?

喜夏-厌秋 提交于 2019-12-25 00:30:31

问题


I have a save() method, not really sure how to test. below is my code.

public interface IRepository<T>
{
    T Get(int id);
    void Save(T item);
    void Delete(int id);
}

save method doesn't return any values back, I cannot compare the value. however, I already have 4 users, after adding another one, I only check the total number of users, is it enough to test it?

[Test]
public void Add_a_new_smoothie_user_should_return_total_5_users()
{
    // Arrange

    var totalUsers = _users.Count();

    _mockUserRepository.Setup(s => s.Save(It.IsAny<User>()))
        .Callback((User user) => _users.Add(user));

    var newUser = new User
                      {
                          Id = 3,
                          Email = "newuser@test.com",
                          Password = "1234567".Hash(),
                          Firstname = "",
                          Lastname = "",

                          CreatedDate = DateTime.Now,
                          LastLogin = DateTime.Now,

                          AccountType = AccountType.Smoothie,
                          DisplayName = "",
                          Avatar = "",
                          ThirdPartyId = "",
                          Status = Status.Approved,
                          Ip = "127.0.0.1"
                      };

    // Act

    _mockUserRepository.Object.Save(newUser);

    // Assert

    Assert.AreEqual(5, _users.Count());
    Assert.AreEqual(1, _users.Count() - totalUsers);
}

回答1:


You are mocking the part of the functionality you are trying to test. These tests will prove nothing, any other than Add() method of the data type you are holding the users. In the end it doesn't give any ideas if your repository is working.

You should try to implement a Database Sandbox for testing your repository functionality.




回答2:


Never write tests for mocked code, because those tests actually do not test anything (well, except mocking framework implementation).

How to create interfaces with test-first approach? It's easy. Consider you have some FooController, which requires some data. At some point (during writing tests for controller) you decide, that there will be some dependency, which will provide that data to controller (yep, repository). Your current controller test requires some functionality to get some Bar object from data storage. So, you write test

Mock<IBarRepository> repositoryMock = new Mock<IBarRepository>();
repositoryMock.Setup(r => r.GetById(It.IsAny<int>()).Returns(new Bar());
FooController controller = new FooController(repositoryMock.Object);
controller.Exercise();

This test will not compile, because at this point you don't have IBarRepository interface, which is needed by controller. You create this interface. And you also add method GetById to this interface. After that you implement controller.

Good news - when controller will be finished, you will have IBarRepository interface definition, which has API very convenient for controller.

Next step is creating IBarRepository implementation. I rarely write tests for repositories. But, you can do it several ways:

  • If your have data access code, which is used by repository (ORM framework, ADO.NET classes, etc), you can mock these dependencies and verify that your repository implementation makes all required calls to underlying data access code. These tests are pretty brittle. And do not give you much benefit, because rarely repositories contain complex business logic.
  • You can do integration testing with real database (e.g. in-memory SQLite) and verify that data is really CRUD-ed in database tables. Those tests also brittle and very time-consuming. But in this case you will be sure, that repository works as it should.



回答3:


Where your repository is saving? If it is saving in some file, then you can compare your file with some model file (gold) where everything was manually checked and is ok. If is some database then you should mock your database interface, log all insert queries and then compare log with ideal log.



来源:https://stackoverflow.com/questions/11459521/moq-how-to-test-the-save-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!