是否可以使用 Moq 在 C# 中模拟模拟的 "type name"?

Is it possible to mock the "type name" of a mock in C# using Moq?

我正在用 C#(基于 .NET Core)开发一个具有模块化行为的聊天机器人。我想要开发的行为之一是 "admin" 模块,该模块(以及其他功能)应该允许管理员通过名称动态启用或禁用其他行为。

我希望管理模块通过检查其类型信息并执行类似以下操作来确定行为的名称:

var name = behaviour.GetType().GetTypeInfo().Name.Replace("Behaviour", string.Empty).ToLowerInvariant();

在我首先编写的 BDD 规范中,我试图设置一个 "behaviour chain" 由管理模块(被测系统)和模拟行为组成。测试涉及发送应导致管理模块启用或禁用模拟行为的命令。

这是我到目前为止所做的:

public BehaviourIsEnabled() : base("Admin requests that a behaviour is enabled")
{
    var mockTypeInfo = new Mock<TypeInfo>();
    mockTypeInfo.SetupGet(it => it.Name).Returns("MockBehaviour");

    var mockType = new Mock<Type>();
    mockType.Setup(it => it.GetTypeInfo()).Returns(mockTypeInfo.Object);

    // TODO: make mock behaviour respond to "foo"
    var mockBehaviour = new Mock<IMofichanBehaviour>();
    mockBehaviour.Setup(b => b.GetType()).Returns(mockType.Object);

    this.Given(s => s.Given_Mofichan_is_configured_with_behaviour("administration"), AddBehaviourTemplate)
        .Given(s => s.Given_Mofichan_is_configured_with_behaviour(mockBehaviour.Object),
                "Given Mofichan is configured with a mock behaviour")
            .And(s => s.Given_Mofichan_is_running())
        .When(s => s.When_I_request_that_a_behaviour_is_enabled("mock"))
            .And(s => s.When_Mofichan_receives_a_message(this.JohnSmithUser, "foo"))
        .Then(s => s.Then_the_mock_behaviour_should_have_been_triggered())
        .TearDownWith(s => s.TearDown());
}

当我 运行 时的问题是 GetTypeInfo()Type 上的扩展方法,所以 Moq 抛出异常:

Expression references a method that does not belong to the mocked object: it => it.GetTypeInfo()

另一种方法,我可以只添加 Name 属性 到 IMofichanBehaviour,但我不喜欢在生产代码中添加任意 methods/properties 的想法那只是为了测试代码的好处。

使用满足被嘲笑的假 class 来保持简单。

public class MockBehaviour : IMofichanBehaviour { ... }

然后测试看起来像

public BehaviourIsEnabled() : base("Admin requests that a behaviour is enabled") {

    // TODO: make mock behaviour respond to "foo"
    var mockBehaviour = new MockBehaviour();


    this.Given(s => s.Given_Mofichan_is_configured_with_behaviour("administration"), AddBehaviourTemplate)
        .Given(s => s.Given_Mofichan_is_configured_with_behaviour(mockBehaviour),
                "Given Mofichan is configured with a mock behaviour")
            .And(s => s.Given_Mofichan_is_running())
        .When(s => s.When_I_request_that_a_behaviour_is_enabled("mock"))
            .And(s => s.When_Mofichan_receives_a_message(this.JohnSmithUser, "foo"))
        .Then(s => s.Then_the_mock_behaviour_should_have_been_triggered())
        .TearDownWith(s => s.TearDown());
}