gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:39:14 24 4
gpt4 key购买 nike

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

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

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

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

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

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()

另一种方法是,我可以只向 IMofichanBehaviour 添加一个 Name 属性,但我不喜欢向生产代码添加任意方法/属性的想法,这只是确实是为了测试代码的好处。

最佳答案

使用满足其模拟的假类来保持简单。

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());
}

关于c# - 是否可以使用 Moq 在 C# 中模拟模拟的 "type name"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40573624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com