jeudi 28 janvier 2016

Unable to cast object of type 'Castle.Proxies.IAvailsContextProxy' to type 'MyApp.Web.AvailsClient.AvailsContext'. using Moq and Unit test

I am writing a unit test and am getting a run time error Unable to cast object of type 'Castle.Proxies.IAvailsContextProxy' to type 'MyApp.Web.AvailsClient.AvailsContext'. when I run my unit test. I don't know if I am setting up the clientMock incorrectly or is the problem in my AvailsRequestService code. Any feedback would be appreciated

Here is my unit test

[Test]
        public async Task GetAllMathcingAsync_Should_Return_All()
        {
            // Arrange
            var fixture = new Fixture().Customize(new IgnoreVirtualCustomization());

            var availRequest = fixture.Create<AvailsRequest.AvailRequest>();

            var availRequestRepository = new Mock<AvailRequest>();

            var clientMock = new Mock<AvailsRequest.IAvailsContext>();
            clientMock.Setup(c => c.AvailRequestSearch(null, null, null, null, null, null)).ReturnsAsync(new []{ availRequest });

            var service = CreateService(client: clientMock.Object);

            // Act
            var actual = await service.GetAllMatchingAsync(null, null, null, null, null, null);

            // Assert
            availRequestRepository.VerifyAll();
        }

        private static AvailsRequestService CreateService(IMappingEngine mapper = null,
                                                          AvailsRequest.IAvailsContext client = null)
        {
            return new AvailsRequestService(
                mapper ?? AutoMapperHelper.GetMappingEngine(new AvailsRequestClientProfile()),
                client ?? Mock.Of<AvailsRequest.IAvailsContext>());
        }

Here is my AvailsRequestService code

private readonly AvailsContext _availsContext;
private readonly IMappingEngine _mapper;

public AvailsRequestService(IMappingEngine mapper,
                             IAvailsContext availsContext)
{
    _mapper = mapper;
    _availsContext = (AvailsContext)availsContext; //This is the line that causes the error
}

Here is the method AvailRequestSearch

public Task<IEnumerable<AvailRequest>> AvailRequestSearch(Guid? advertiserId, Guid? agencyId, int? channelInt, DateTime? endDate, DateTime? startDate, int? Status)
    {
        var fixture = new Fixture();

        var result = fixture.CreateMany<AvailRequest>().Where(x => (advertiserId ==null || x.AdvertiserId == advertiserId) &&
                                                        (agencyId == null || x.AgencyId == agencyId) && (channelInt.HasValue || x.ChannelInt == channelInt) &&
                                                        (endDate == null || x.EndDate <= endDate) && (startDate == null || x.StartDate >= startDate));

        return Task.FromResult(result);
    }

Aucun commentaire:

Enregistrer un commentaire