locked
Can a Web Api be tested with Moq? RRS feed

  • Question

  • User-94355476 posted

    I'm building an API that will interact with LibGit2Sharp.  I had several endpoints quickly up & running but then was faced with the requirement of writing tests for them, something I don't have a lot of experience with.  But, after some refactoring, I was able to successfully build some unit tests.  Here's an example of one:

            [Fact]
            public void Ensure_GetAllFiles_ReturnsCorrectNumberOfFiles()
            {
                // Arrange
                var mockList = new List<string> { "articles.html", "categories.html", "homepage.html" };
                var gitRepositoryMock = new Mock<IGitRepository>();
                gitRepositoryMock.Setup(gr => gr.GetAllFiles(It.IsAny<string>(), It.IsAny<string>())).Returns(mockList);
    
                // Act
                var response = gitRepositoryMock.Object.GetAllFiles("SomeOrg", "SomeRepo");
    
                // Assert
                Assert.Equal(3, response.Count);
            }

    On the advice of an experienced colleague, I referenced the GitServices project from the Unit Tests project.  In this way, my unit tests run very quickly.  But he strongly advised me to have Integration Tests actually testing against the running service.  This makes sense because they'll prove a lot more more whether things are working or not.

    I figure that I have two possible ways that I can build the Integration Tests:

    1. Using preset "dummy" repos that will be cloned, tested, and then destroyed.  This appears to be the way such tests are done in the LibGit2Sharp project.
    2. By injecting the Mock Repository into the desired GitServices Controller.  In this way, the Mock Repo would be utilized, not an actual Git repo.

    The main intention of this post is to find out if #2 is even possible.  I've read several articles, tried several approaches, but with no success so far.  Simply put, once I've instantiated a mock repo, such is as shown in the sample code above, what code would be necessary to inject it into the controller?

    Note: I'm using Ninject, in case that matters.

    Robert

    Thursday, December 29, 2016 2:44 AM

All replies