Why does NServiceBus sends subscription messages in my integration / unit tests?

When you reference the handlers assembly from your test assembly and this assembly initializes a bus instance and the endpoint to send messages to is a publisher it can happen that you see multiple messages being send to the endpoint. while you expected less messages. Inspecting the messages indicates subscription acknowledgement messages and you wonder why that is as you don’t want your test project to subscribe to anything at all! This happens because NServiceBus scans all available assemblies for messages handlers and when it finds these then it will subscribe to the events which results in the messages that you see in the (journal) queues.

Luckily this behavior can be disabled by calling .DoNotAutoSubscribe() during bus initialization as shown in the following example:

var bus = Configure.With()
	.DefineEndpointName("integrationtests")
	.DefiningCommandsAs(MessageNamingConvention.IsCommand)
	.DefiningEventsAs(MessageNamingConvention.IsEvent)
	.DefiningMessagesAs(MessageNamingConvention.IsMessage)
	.UnityBuilder()
	.XmlSerializer()
	.MsmqTransport()
		.IsTransactional(true)
		.PurgeOnStartup(false)
	.UnicastBus()
		.ImpersonateSender(false)
	.DoNotAutoSubscribe()	// Needed as otherwise the client will subscribe to event messages because handler assembly is references and scanned by NServiceBus.
	.CreateBus()
	.Start();

NServiceBus v3 does not automatically create queues

Queues are not automatically created anymore since NServiceBus v3. Queues are now created during the installation phase which you usually do not have in web apps or test apps. You can still have the old behavior by triggering the installation during bus creation. Make the following change to trigger this.

// From:
.Start()
// To:
.Start(() => Configure.Instance.ForInstallationOn<Windows>().Install());
  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta