'UnitTest ASP.Net Core Web API that using unit of work repository pattern

How I can set up the unitOfWork mock object in a test method?

I would create a test for the GetHomework method of an API project that uses the unit of work repository pattern. But I couldn't create a test method.

API:

[Route("api/[controller]")]
[ApiController]
public class HomeworkController : ControllerBase
{
    private readonly IUnitOfWork _unitOfWork;

    public HomeworkController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    // GET: api/Homework/5
    [HttpGet("{id}")]
    public ActionResult<HomeworkDto> GetHomework(int id)
    {
        var Homework = _unitOfWork.Homework.Get(id);

        if (Homework == null)
        {
            return NotFound();
        }

        return Ok(_mapper.Map<HomeworkDto>(Homework));
    }
}

Test:

public class UnitTests
{
    [Fact]
    public void GetHomework_WithUnexistingItem_ReturnsNotFound()
    {
        //Arrange
        var unitOfWorkStub = new Mock<IUnitOfWork>();
        unitOfWorkStub.Setup(u => u.Homework);

        var controller = new HomeworkController(unitOfWorkStub.Object);

        //Act
        var result = controller.GetHomework(id: 100);

        //Assert
        Assert.IsType<NotFoundResult>(result.Result);

    }
}

Any advice or assistance would be greatly appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source