我正在尝试在创建新实体时测试一些逻辑。要么:
我的设置是这样的:
// 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
仍然失败。