Junior — Middle
How can you apply unit testing to verify the Consumer interface?
sobes.tech AI
Answer from AI
In C#, the Consumer interface is usually represented by the delegate Action<T>, which takes a parameter and returns nothing. For unit testing code that uses Consumer (e.g., Action<T>), you can use mocks or verify side effects of the call.
Example using Moq to verify that Consumer was called with the expected parameter:
using Moq;
// Interface with a method accepting a Consumer
public interface IProcessor
{
void Process(Action<string> consumer);
}
// Test
var mockConsumer = new Mock<Action<string>>();
IProcessor processor = ...; // object that calls consumer
processor.Process(mockConsumer.Object);
// Verify that consumer was called with a specific argument
mockConsumer.Verify(c => c(It.Is<string>(s => s == "expected value")), Times.Once);
If you are not using mocking frameworks, you can implement your own Action<T> that records calls in a list or changes state to verify it was called correctly.
Thus, unit testing Consumer reduces to verifying that it is called with the correct parameters and at the right time.