gpt4 book ai didi

unit-testing - 如何使用 Moq 测试对 NServiceBus IBus.Publish() 的调用?

转载 作者:行者123 更新时间:2023-12-03 13:44:47 31 4
gpt4 key购买 nike

下面的代码编译、运行,完全符合我的预期 - GreetingPublisher 在引发事件时调用 bus.Publish() - 但 Moq 设置不匹配:

using Moq;
using NServiceBus;
using NUnit.Framework;

namespace MyProject.Greetifier.Tests {
[TestFixture]
public class GreetingPublisher_Bus_Integration_Tests {
[Test]
public void Greeting_Is_Published_To_Bus() {
var mockGreeter = new Mock<IGreeter>();
var mockBus = new Mock<IBus>();
mockBus.Setup(bus => bus.Publish<IMessage>(It.IsAny<IMessage>()))
.Verifiable();
var Greetifier = new GreetingPublisher(mockGreeter.Object,
mockBus.Object);
mockGreeter.Raise(m => m.Greet += null, "world");
mockBus.Verify();
}
}

public class HelloMessage : IMessage {
public string Name { get; set; }
public HelloMessage(string name) { this.Name = name; }

}

public class GreetingPublisher {
private readonly IGreeter greeter;
private readonly IBus bus;

public GreetingPublisher(IGreeter greeter, IBus bus) {
this.greeter = greeter;
greeter.Greet += handleGreetEvent;
this.bus = bus;
}

void handleGreetEvent(string name) {
bus.Publish(new HelloMessage(name));
}
}

public delegate void GreetingEvent(string name);

public interface IGreeter {
event GreetingEvent Greet;
}
}

在运行测试时,我得到:
Test 'MyProject.Greetifier.Tests.GreetingPublisher_Bus_Integration_Tests.Greeting_Is_Published_To_Bus' failed:
Moq.MockVerificationException : The following setups were not matched:
IBus bus => bus.Publish<IMessage>(new[] { It.IsAny<IMessage>() })
at Moq.Mock.Verify()
D:\Projects\MyProject\src\MyProject.Greetifier.Tests\Program.cs(15,0): MyProject.Greetifier.Tests.GreetingPublisher_Bus_Integration_Tests.Greeting_Is_Published_To_Bus()

我错过了一些明显的东西吗?

最佳答案

如果我没看错,你的代码会调用 IBus.Publish<HelloMessage>而不是 IBus.Publish<IMessage> .

(编辑:我替换了

mockBus.Setup(bus => bus.Publish<IMessage>(It.IsAny<IMessage>()))
.Verifiable();

和:
mockBus.Setup(bus => bus.Publish<HelloMessage>(It.IsAny<HelloMessage>()))
.Verifiable();

它按预期工作 - 迪伦)

关于unit-testing - 如何使用 Moq 测试对 NServiceBus IBus.Publish() 的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6762311/

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