Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a method with Action<T>

I am new with Unit Testing, would be happy to know if I am making any mistake or not proceeding the right direction.

Here is the situation:

I am trying to test a method (MethodUnderTest) which calls another method(MethodWithAction) which takes Action<T> as argument. I want to mock MethodWithAction, but test the logic based on the return value.

Here is the structure:

interface IInterface
{
    void MethodWithAction(Action<string> action);
}

class MyClass : IInterface
{
    public void MethodWithAction(Action<string> action)
    {
        string sampleString = "Hello there";
        action(sampleString);
    }
}

class ClassUnderTest
{
    public IInterface Obj = new MyClass();
    public string MethodUnderTest()
    {
        string stringToBeTested = string.Empty;

        Obj.MethodWithAction(str =>
        {
            if (str.Contains("."))
                stringToBeTested = string.Empty;
            else
                stringToBeTested = str.Replace(" ", string.Empty);
        });
        return stringToBeTested;
    }
}

My test method goes like this:

[TestMethod]
[DataRow("Hello, World", "Hello,World")]
[DataRow("Hello, World.","")]
[DataRow("Hello", "Hello")]
public void MethodUnderTestReturnsCorrectString(string sampleString, string expected)
{
    var mockObj = new Mock<IInterface>();
    mockObj.Setup(m=>m.MethodWithAction(It.IsAny<Action<string>>))
    .Callback(???);
    ClassUnderTest sut = new ClassUnderTest();
    sut.Obj=mockObj.Object;
    string actual = sut.MethodUnderTest();
    Assert.Equal(expected, actual);
 }

I would like to know what goes at the place of ??? in the test, or is there entirely different approach for this problem?

like image 343
Anjesh Aggarwal Avatar asked May 08 '26 01:05

Anjesh Aggarwal


1 Answers

Grab the action parameter that was passed to the mock in the call back and invoke it with the sample string.

mockObj
    .Setup(m => m.MethodWithAction(It.IsAny<Action<string>>))
    .Callback((Action<string> action) => action(sampleString));

Reference Moq Quickstart to get a better understanding of how to use this mocking framework.

like image 167
Nkosi Avatar answered May 10 '26 14:05

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!