Repository Pattern and unit testing from memory

前端 未结 1 1396
Happy的楠姐
Happy的楠姐 2021-02-01 23:59

I have seen some implementations of the Repository Pattern, very simple and intuitive, linked form other answers here in stackoverflow

http://www.codeproject.com/Tips/30

1条回答
  •  天涯浪人
    2021-02-02 00:30

    I'd suggest to use a mocking library like Moq or RhinoMocks. A nice tutorial using Moq can be found here.

    Before you decide which one you'll use, the followings might help:

    • http://graemef.com/blog/2011/02/10/A-quick-comparison-of-some-.NET-mocking-frameworks/

    • http://jimmykeen.net/articles/09-jul-2012/mocking-frameworks-comparison-part-1-introduction

    Additional information : Comparison of unit test framework can be found here.


    UPDATE following OP's request

    Create a in memory database

    var bookInMemoryDatabase = new List
    {
        new Book() {Id = 1, Name = "Book1"},
        new Book() {Id = 2, Name = "Book2"},
        new Book() {Id = 3, Name = "Book3"}
    };
    

    Mock your repository (I used Moq for the following example)

    var repository = new Mock>();
    

    Set up your repository

    // When I call GetById method defined in my IRepository contract, the moq will try to find
    // matching element in my memory database and return it.
    
    repository.Setup(x => x.GetById(It.IsAny()))
              .Returns((int i) => bookInMemoryDatabase.Single(bo => bo.Id == i));
    

    Create a library object by passing your mock object in constructor parameter

    var library = new Library(repository.Object);
    

    And finally some tests :

    // First scenario look up for some book that really exists 
    var bookThatExists = library.GetByID(3);
    Assert.IsNotNull(bookThatExists);
    Assert.AreEqual(bookThatExists.Id, 3);
    Assert.AreEqual(bookThatExists.Name, "Book3");
    
    // Second scenario look for some book that does not exist 
    //(I don't have any book in my memory database with Id = 5 
    
    Assert.That(() => library.GetByID(5),
                       Throws.Exception
                             .TypeOf());
    
    // Add more test case depending on your business context
    .....
    

    0 讨论(0)
提交回复
热议问题