0

I have an interface with a method like this:

public string GetImageSrc(string input);

The implementation of this is below:

    public string GetImageSrc(string input)
    {
        if (input.ContainsImage())
        {
               DoWork();
        }
        return input;
    }

My string extension for ConatinsImage is:

    public static bool ContainsImage(this string input)
    {
        if (!string.IsNullOrEmpty(input))
        {
            return input.Contains("img");
        }
        return false;
    }

DoWork is a private method in the class. I am writing Unit Tests for the class - I am passing null to the method and doing an assert that null is returned. However is there a way I can Assert the invocation of the DoWork private method is None for a null input?

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116
  • Does this answer your question? [How do you unit test private methods?](https://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods) – Pavel Anikhouski Mar 15 '20 at 06:24

1 Answers1

4

I recommend creating a new interface IWorker with a DoWork() method, then inject it into the constructor of the class that contains the GetImageSrc() method. In your unit test, you could then inject a mock object of the interface, and verify DoWork() was called or not:

public interface IWorker
{
    void DoWork();
}

public class YourClass
{
    private readonly IWorker _worker;

    public YourClass(IWorker worker)
    {
        _worker = worker;
    }

    public string GetImageSrc(string input)
    {
        if (input.ContainsImage())
        {
            _worker.DoWork();
        }
        return input;
    }
}

Test using Microsoft.VisualStudio.TestTools.UnitTesting and Moq:

    [TestMethod]
    public void GetImageSrc_GivenNull_ReturnsNull_And_WorkerNotCalled()
    {
        var mockWorker = new Mock<IWorker>();

        var testSubject = new YourClass(mockWorker.Object);
        var response = testSubject.GetImageSrc(null);

        Assert.IsNull(response);
        mockWorker.Verify(x => x.DoWork(), Times.Never());
    }
sspaniel
  • 647
  • 3
  • 10
  • Cheers - just reading this answer as well and maybe need to rethink if I need to do this test..https://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods?rq=1 – Ctrl_Alt_Defeat Mar 14 '20 at 20:23