无法转换类型' Castle.Proxies.IAvailsContextProxy'的对象输入' MyApp.Web.AvailsClient.AvailsContext'。使用Moq和单元测试

时间:2016-01-28 18:19:31

标签: c# unit-testing

我正在编写单元测试,并且遇到运行时错误Unable to cast object of type 'Castle.Proxies.IAvailsContextProxy' to type 'MyApp.Web.AvailsClient.AvailsContext'。当我进行单元测试时。我不知道我是否错误地设置了clientMock,或者我的AvailsRequestService代码中存在问题。任何反馈都将不胜感激

这是我的单元测试

[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>());
        }

这是我的AvailsRequestService代码

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
}

以下是方法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);
    }

1 个答案:

答案 0 :(得分:1)

您正在将构造函数中的接口类型实例装箱为具体类型。 为什么不存储对interface参数的引用?

问候