dimanche 20 décembre 2015

Mocking delegates with Moq

I have an interface:

public interface IRepeater
{
    void Each(string path, Action<string> action);
}

I want to mock this interface using Moq. Now I can obviously do the following:

var mock = new Mock<IRepeater>();
mock.Setup(m => m.Each(It.IsAny<string>(), It.IsAny<Action<string>>());

However, to aid testing I want to be able to mock the string that gets passed to the Action<string>. Can this be done with Moq? If yes, how?

Update

To clarify I am testing a different class that has a dependency on IRepeater. I want to mock IRepeater.Each so I can control the string that the Action gets so I can test the behaviour.

Example

So if I have a class like so.

public class Service
{
    private readonly IRepeater _repeater;

    public Service(IRepeater repeater)
    {
        _repeater = repeater;
    }

    public string Parse(string path)
    {
        var builder = new StringBuilder();

        _repeater.Each(path, line => builder.Append(line));

        return builder.ToString();
    }
}

How do I mock IRepeater.Each so that I can test Service.Parse?

Aucun commentaire:

Enregistrer un commentaire