使用IEnumerable合并XUnit中的两个模拟对象

时间:2018-07-03 10:05:51

标签: c# unit-testing moq ienumerable xunit.net

我正在尝试在创建新实体时测试一些逻辑。要么:

  1. 该实体没有关联的功能(在这种情况下,它获得了所有现有的核心功能),或者
  2. 该实体具有一些关联的功能(在这种情况下,它获得了这些功能∪所有现有的核心功能)。

我的设置是这样的:

// Non-core functionality
var functionality = new Mock<IFunctionality>();
functionality.Setup(x => x.Id).Returns(Guid.NewGuid());

// Entity with non-core functionality
var entity = new Mock<IEntity>();
entity.Setup(x => x.Functionalities).Returns(new List<IFunctionality>
{
    functionality.Object
});

// Core functionality
var coreFunctionality = new Mock<IFunctionality>();
coreFunctionality.Setup(x => x.Id).Returns(Guid.NewGuid());
coreFunctionality.Setup(x => x.IsCore).Returns(true);

// All functionalities
var functionalities = new List<IFunctionality>
{
    functionality.Object,
    coreFunctionality.Object
};

var functionalityManager = new Mock<IFunctionalityManager<IFunctionality>>();
functionalityManager.Setup(x => x.GetCoreFunctionalities()).Returns(new List<IFunctionality>
{
    coreFunctionality.Object
});

var service = new EntityService<IEntity>(functionalityManager.Object);

然后我打电话:

var create = service.Create(entity.Object);

该服务实现上述逻辑,如下所示:

var coreFunctionalitites = _functionalityManager.GetCoreFunctionalities();
entity.Functionalities = entity.Functionalities != null
    ? entity.Functionalities.Union(coreFunctionalitites).ToList()
    : coreFunctionalitites.ToList();

这可以按实际预期(即,发布到API时)运行,但是以下断言在测试时始终会失败:

Assert.Equal(functionalities.Count, create.Functionalities.Count);

调试测试时,我可以在即时窗口中看到coreFunctionalities确实包含coreFunctionality(带有Guid):

coreFunctionalitites.First()
{Mock<IFunctionality:00000002>.Object}
    Id: {b0bbb77e-3e1a-415b-ac78-c36f1714ecf9}
    IsCore: true
    Mock (Castle.Proxies.IFunctionalityProxy): {Mock<IFunctionality:00000002>}
    Mock: {Mock<IFunctionality:00000002>}

我还可以将鼠标悬停在entity.Functionalities上方,并查看其中包含functionality(带有单独的Guid):

{Mock<IFunctionality:00000001>.Object}
    Id: {3c4396d3-9667-418e-9287-da56c529cd90}
    IsCore: false
    Mock (Castle.Proxies.IFunctionalityProxy): {Mock<IFunctionality:00000001>}
    Mock: {Mock<IFunctionality:00000001>}

但是当我在立即窗口中尝试entity.Functionalities.First()时,我得到:

error CS1061: 'T' does not contain a definition for 'Functionalities' and no extension method 'Functionalities' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

Union之后,coreFunctionality没有添加到entity.Functionalities中。我是否在安装程序中缺少某些东西可以使它正常工作?

更新:

我更改了服务中的相关方法,以使用特定的IEntity接口(以消除泛型变量)。有了这一更改,我现在可以在“即时Windows”中成功查看entity.Functionalities.First(),而不会出现错误。但是Union仍然失败。

0 个答案:

没有答案