0
namespace Producer.UnitTests.Controllers
{
    public class ParticipantsControllerTests
    {
        private readonly Mock<IDbConnectionFactory> _mockDbConnectionFactory;
        private readonly Mock<ILogger<Participant>> _mockLogger;
        private readonly Mock<IMapper> _mapper;
        public ParticipantsControllerTests()
        {
            _mockDbConnectionFactory = new Mock<IDbConnectionFactory>();
            _mockLogger = new Mock<ILogger<Participant>>();
            _mapper = new Mock<IMapper>();
        }

        [Fact]
        public async Task Get_ShouldReturnOkResponse_WhenIdExists()
        {
            var expectedSport = new Participant { Id = 1, Name = "Matan"};
            var mockDb = new Mock<IDbConnection>();
            mockDb.Setup(x => x.LoadSingleByIdAsync<Participant>(1, It.IsAny<string[]>(), It.IsAny<CancellationToken>())).ReturnsAsync(expectedSport);
            _mockDbConnectionFactory.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>())).ReturnsAsync(mockDb.Object);
            var controller = new ParticipantsController(_mockDbConnectionFactory.Object, _mockLogger.Object, _mapper.Object);

            var result = await controller.Get(1);

            Assert.IsType<OkObjectResult>(result);
            var okResult = (OkObjectResult)result;
            var sport = (Sport)okResult.Value;
            Assert.Equal(expectedSport.Id, sport.Id);
            Assert.Equal(expectedSport.Name, sport.Name);
        }
    }
}

the setup on LoadSingleByIdAsync and OpenAsync isn't working because they are extension methods. what can I do to fix that? The error I get: System.NotSupportedException : Unsupported expression: x => x.LoadSingleByIdAsync((object)1, It.IsAny<string[]>(), It.IsAny()) Extension methods (here: OrmLiteReadApiAsync.LoadSingleByIdAsync) may not be used in setup / verification expressions.

Matan_Ati
  • 21
  • 4
  • you can't. Mocking is about members you can override, this is if the method is abstract or virtual. – MakePeaceGreatAgain Mar 01 '23 at 14:10
  • Do I have to use something else than Mock then? like FakeItEasy? – Matan_Ati Mar 01 '23 at 14:14
  • If these extension methods are coming from Dapper... You can look at https://stackoverflow.com/questions/52414562/how-to-mock-querymultiple-using-moq-dapper – Chetan Mar 01 '23 at 14:18
  • If that extension method is written by you then you need to mock the behavior which is inside the method. That will be mostly IDbConnection method or properties, you are using in that extension method, you will have to mock. – Chetan Mar 01 '23 at 14:27

0 Answers0