Unit Testing ServiceBus.Message. How to set value for SystemProperties.LockToken?
I created a wrapper method GetLockToken()
which returns the LockToken
string if it set on the message, else it returns null (instead of throwing an exception).
private string GetLockToken(Message msg)
{
// msg.SystemProperties.LockToken Get property throws exception if not set. Return null instead.
return msg.SystemProperties.IsLockTokenSet ? msg.SystemProperties.LockToken : null;
}
The original method call to CompleteAsync()
is now modified to:
await _client.CompleteAsync(GetLockToken(message));
Note: The above change doesn't change the expected behavior! In a production scenario, call to CompleteAsync(null)
would still throw an exception :) (as desired).
With above changes now I can set up my mocks as such:
var mock= new Mock<IQueueClient>();
mock.Setup(c => c.CompleteAsync(/*lockToken*/ null))
.Returns(Task.CompletedTask);
Here is how to create a Message for testing and set the LockToken:
var message = new Message();
var systemProperties = message.SystemProperties;
var type = systemProperties.GetType();
var lockToken = Guid.NewGuid();
type.GetMethod("set_LockTokenGuid", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(systemProperties, new object[] { lockToken });
type.GetMethod("set_SequenceNumber", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(systemProperties, new object[] { 0 });
I wish that I had been able to come up with something that did not involve reflection.