我有这个代码来模拟一个Rebus MessageContext
IBus fakeBus;
IMessageContext messageContext;
[TestInitialize]
public void TestInitialize()
{
fakeBus = new FakeBus();
var mock = new Mock<IMessageContext>();
mock.Setup(m => m.ReturnAddress).Returns("queuename");
mock.Setup(h => h.Headers).Returns(new Dictionary<string, object>());
mock.Setup(m => m.Items).Returns(new Dictionary<string, object>());
mock.Setup(m => m.RebusTransportMessageId).Returns(Guid.NewGuid().ToString());
messageContext = mock.Object;
var fakeContext = FakeMessageContext.Establish(messageContext); // error here
}
但是最后一行返回下面的堆栈跟踪。我遗漏了什么?
旁注:我仍然在Rebus 0.84。
Result StackTrace:
at Rebus.MessageContext.Establish(IMessageContext messageContext, Boolean overwrite)
at Rebus.Testing.FakeMessageContext.Establish(IMessageContext messageContext)
at MyApp.Messaging.Tests.Handlers.RegisterPaymentCallbackTests.TestInitialize() in C:CUT.TestsHandlersRegisterPaymentCallbackTests.cs:line 57
Result Message: Initialization method MyApp.Tests.Handlers.RegisterPaymentCallbackTests.TestInitialize threw exception. System.InvalidOperationException: Could not find a transaction context. There should always be a transaction context - though it might be a NoTransaction transaction context..
我自己并没有真正使用假消息上下文,因为我通常发现使用SagaFixture
或对稍大的单元进行单元测试更容易。
当我查看旧的Rebus代码时,我可以看到所有执行FakeMessageContext
的测试都首先建立了一个事务上下文,如下所示:
using (TransactionContext.None())
using (FakeMessageContext.Establish(fakeContext))
{
// do stuff
}
所以必须这样做:)