Search code examples
c#unit-testingmoqxunit

Using Moq with Xunit - Unit testing .net core API


I'm trying to unit test a controller and I created a fake class that Implements an Interface.

public class UnitTest1   
    {
        GrantProgramsController _controller;
        IBLGrantProgram _grant;
        readonly ILogger<GrantProgramsController> _logger;
        public UnitTest1()
        {
             _grant = new BLGrantProgramFake();
            _logger = new Logger<GrantProgramsController>(new NullLoggerFactory());
            _controller = new GrantProgramsController(_grant, _logger);
          
        }
        //tests for get method
        [Fact]
        public void Get_whencalled_returnsokresult()
        {
            // Act
            var okResult = _controller.GetGrantProgram();
            // Assert
            Assert.IsType<OkObjectResult>(okResult.Result);
        }
----------

But, I'm trying to use Moq framework and mock the interface instead of creating a fake implementation for the interface.

 public UnitTest1()
        {
            // _grant = new BLGrantProgramFake();
            _grant = new Mock<BLGrantProgram>();
            _logger = new Logger<GrantProgramsController>(new NullLoggerFactory());
            _controller = new GrantProgramsController(_grant, _logger);
          
        }

but error pops up for mocking. can somebody point out whether if this is not the way. I'm new to this. Thanks in advance.


Solution

  • This may just be an assignment issue since when using MOQ the assignment to the actual type will need to come from the Mock<T>.Object property

    public UnitTest1() {
        _grant = new Mock<IBLGrantProgram>().Object; //<---
        _logger = new Logger<GrantProgramsController>(new NullLoggerFactory());
        _controller = new GrantProgramsController(_grant, _logger);
    }
    

    If there are members to be configured then the Mock<T> would still be needed to setup the expectations.

    For example

    public UnitTest1() {
       _grant = new Mock<IBLGrantProgram>().Object; //<--- mock assigned
    
        //extract Mock<T> and setup expectations.
        Mock.Get(_grant).Setup(_ => _.SomeMember()).Returns(someValue);
    
        _logger = new Logger<GrantProgramsController>(new NullLoggerFactory());
        _controller = new GrantProgramsController(_grant, _logger);
    }
    

    I would suggest you Reference Moq Quickstart to get a better understanding of how to use that library.