C
C#2y ago
Denis

❔ Capture parameter value with Moq decorated with the 'in' keyword

Hello! I'm writing Unit Tests for a library with a lot of structs, which utilizes the in keyword to avoid unnecessary copies. The Moq library allows you to capture passed values to methods. For example
Action<string> newMessageHandler;
var captureMatch = new CaptureMatch<Action<string>>(capture => newMessageHandler = capture);
var messageManagerMock = new Mock<IMessageManager>();

messageManagerMock.Setup(managerInstance => managerInstance.Start(Capture.With(captureMatch)));
Action<string> newMessageHandler;
var captureMatch = new CaptureMatch<Action<string>>(capture => newMessageHandler = capture);
var messageManagerMock = new Mock<IMessageManager>();

messageManagerMock.Setup(managerInstance => managerInstance.Start(Capture.With(captureMatch)));
I've found solutions for capturing ref and out parameters. But nothing for in. I tried solving this some time ago, and only just now thought of asking here, so I do not have more fresh examples.
2 Replies
Denis
DenisOP2y ago
Assume we have the following class we want to mock, and capture parameters passed to it:
public interface IMessageManager
: IDisposable
{
/// <summary>
/// Starts the manager
/// </summary>
/// <param name="messageHandler">Incoming message handler</param>
void Start(Action<string> messageHandler);

/// <summary>
/// Removes a message
/// </summary>
/// <param name="metadata">Message metadata reference to remove</param>
/// <returns>True if operation was successful</returns>
bool Remove(in XMLMessageMetadata metadata);

/// <summary>
/// Creates a message
/// </summary>
/// <param name="message">Message to create</param>
/// <param name="path">Path to create the message at</param>
/// <returns>True if operation was successful</returns>
bool Create(in XMLMessage message, string path);
}
public interface IMessageManager
: IDisposable
{
/// <summary>
/// Starts the manager
/// </summary>
/// <param name="messageHandler">Incoming message handler</param>
void Start(Action<string> messageHandler);

/// <summary>
/// Removes a message
/// </summary>
/// <param name="metadata">Message metadata reference to remove</param>
/// <returns>True if operation was successful</returns>
bool Remove(in XMLMessageMetadata metadata);

/// <summary>
/// Creates a message
/// </summary>
/// <param name="message">Message to create</param>
/// <param name="path">Path to create the message at</param>
/// <returns>True if operation was successful</returns>
bool Create(in XMLMessage message, string path);
}
And again, the XMLMessage and XMLMessageMetadata are readonly structs
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server