尝试模拟Azure搜索模型上的字段数时不支持的表达式

问题描述

我正在尝试对以下方法进行单元测试:

 public bool CompareIndexEquality(Index resultBody,Type indexType)
        {
            var properties = indexType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            if (properties.Count() == resultBody.Fields.Count)
            {
                HavePropertyAttributesChanged(properties);
            }
            return false;
        }

我的尝试是这样:

[Test]
        public void CompareIndexEquality_AnyCase_ReturnsTrueIfAttributesmatch()
        {
            var compareSearchIndexService = new CompareSearchIndexService();
            var indexTypeMock =  new Mock<Type>();
            var resultBodyMock = new Mock<Microsoft.Azure.Search.Models.Index>();
            var lookUpIndexModel = new LookUpIndexModel();
            PropertyInfo[] propertyInfo = lookUpIndexModel.GetType().GetProperties();


            indexTypeMock.Setup(r => r.GetProperties(BindingFlags.Instance | BindingFlags.Instance)).Returns(propertyInfo);
            resultBodyMock.Setup(r => r.Fields).Returns(new List<Field>());
            var result = compareSearchIndexService.CompareIndexEquality(resultBodyMock.Object,indexTypeMock.Object);
            Assert.IsFalse(result);
        }

我收到错误: $ exception {“不支持的表达式:r => r.Fields \ n不可覆盖的成员(此处为Index.get_Fields)不能在设置/验证表达式中使用。”} System.NotSupportedException

有人知道我如何模拟Microsoft.Azure.Search.Models.Index上的字段吗?

谢谢

解决方法

Moq创建模拟类型的实现。如果类型是类,则它将创建一个继承的类,并且该继承的类的成员称为基类。但是为了做到这一点,它必须覆盖成员。如果一个类的成员不能被覆盖(它们不是虚拟的,抽象的),那么Moq不能覆盖它们以添加自己的行为。

我们如何确定是否要嘲笑某些东西?

通常来说,如果我们不想在测试中包括具体的运行时实现,则可以模拟一些东西。我们想同时测试一个课程。

但是在这种情况下,CompareIndexEquality只是一个判断数据的类。 嘲笑它真的没有意义。使用真实的东西一样容易。