【问题标题】:Mock a method returning an interface with NInject Mocking Kernel使用 NInject Mocking Kernel 模拟返回接口的方法
【发布时间】:2024-05-18 17:35:02
【问题描述】:

假设我有一个这样的界面。

public interface ICamProcRepository
{
    List<IAitoeRedCell> GetAllAitoeRedCells();
    IAitoeRedCell CreateAitoeRedCell();
}

如何模拟返回接口和接口对象列表的方法。我正在使用 Ninject.MockingKernel.Moq

var mockingKernel = new MoqMockingKernel();

var camProcRepositoryMock = mockingKernel.GetMock<ICamProcRepository>();

camProcRepositoryMock.Setup(e => e.GetAllAitoeRedCells()).Returns(?????WHAT HERE?????);

camProcRepositoryMock.Setup(e => e.CreateAitoeRedCell()).Returns(?????WHAT HERE?????);

【问题讨论】:

  • 通过创建所需结果的模拟并将它们传递给设置的Returns。通过内核或直接起订量。我不知道 Ninject 能帮到你。

标签: c# unit-testing moq ninject-mockingkernel


【解决方案1】:

在您的情况下,您需要为有问题的模拟接口创建所需结果的模拟,并将它们通过内核或直接 moq 传递到其设置的Returns。我不知道 Ninject 能帮到你,但这是一个简单的起订量示例

var mockingKernel = new MoqMockingKernel();

var camProcRepositoryMock = mockingKernel.GetMock<ICamProcRepository>();

var fakeList = new List<IAitoeRedCell>();
//You can either leave the list empty or populate it with mocks.
//for(int i = 0; i < 5; i++) {
//    fakeList.Add(Mock.Of<IAitoeRedCell>());
//}

camProcRepositoryMock.Setup(e => e.GetAllAitoeRedCells()).Returns(fakeList);

camProcRepositoryMock.Setup(e => e.CreateAitoeRedCell()).Returns(() => Mock.Of<IAitoeRedCell>());

如果模拟对象也需要提供假功能,那么也必须进行相应设置。

【讨论】:

  • 好的,有道理。让我试一试。