Unit Testing Interfaces with Moq

10,522

You are testing mock here, which gives you nothing (because this mock is not used in your real application). In unit-testing you should create and test your real objects, which exist in your real application (i.e. interface implementations). Mocks used for mocking dependencies of objects under test.

So, mock of service adapter will be useful for tests of object, which uses that adapter, e.g. some controller tests:

private FooController _controller; // object under test, real object
private Mock<IServiceAdapter> _serviceAdapter; // dependency of controller

[TestInitialize]
public void Initialize()
{
    _serviceAdapter = new Mock<IServiceAdapter>();
    _controller = new FooController(_serviceAdapter.Object);
}

[TestMethod()]
public void SaveTest()
{
    // Arrange
    string name = "Name1"; 
    string type = "1";
    string parentID = null;

    _serviceAdapter.Setup(x => x.Save(name , type, parentID))
                   .Returns("Success").Verifiable();

    // Act on your object under test!
    // controller will call dependency
    var result =  _controller.Bar(name , type, parentID); 

    // Assert
    Assert.True(result); // verify result is correct
    _serviceAdapter.Verify(); // verify dependency was called
}
Share:
10,522
Morgan Soren
Author by

Morgan Soren

Updated on June 27, 2022

Comments

  • Morgan Soren
    Morgan Soren almost 2 years

    I'm new to Moq and unit testing. I have been doing a unit test and this is the following code:

    private Mock<IServiceAdapter> repository;
    
        [TestInitialize]
        public void Initialize()
        {
            repository= new Mock<IServiceAdapter>();
        }
    
    [TestMethod()]
        public void SaveTest()
        {
            //Setup 
            string Name = "Name1"; 
            string Type = "1";
            string parentID = null;
    
            repository.Setup(x => x.Save(Name , Type, parentID)).Returns("Success").Verifiable();
    
            //Do
            var result = repository.Object.Save(Name , Type, parentID);
            //Assert
            repository.Verify();
        }
    

    My problem is that the test will always return the string that I put in the Returns parameter, in other words, it will always return "success" or whatever I write in its place. I guess thats not right because thats not the real behavior of the service. Anyone knows how I can mirror the real behavior of the "Save" service I'm trying to test? So lets say, if the return string is different from the service method,then the test should fail.

    Edited

    The ServiceAdapter interface its just a wrapper for a Web Service which I call like a REST Service. It's a Web Forms Project.

    I'm doing something like in this post

    How to mock a web service

    Should I create something like a FakeController with Dependency Injection to make it work?