Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq: setting up for a method which returns no value

Tags:

moq

I'm trying to mock out a call to a repository. I can successfully do so when a repository call returns a value by using Setup().Returns:

mock.Setup(m => m.Get(param)).Returns(new CustomObject());

However, when I try to do the same sort of Setup for repository calls which return no values, Moq throws an exception and tells me this method was never called i.e.Expected invocation on the mock exactly 1 times, but was 0 times

Precisely, I'm doing this:

mock.Setup(m => m.UpdateRepository(param1)); // UpdateRepository returns no value
service.DoUpdate(param1);
mock.Verify(m => m.UpdateRepository(param1), Times.Exactly(1));

Note: DoUpdate method only calls repository.UpdateRepository(param1);

Am I not using Moq setup correctly in this instance? Is there a different way to Setup methods which return no value?

Thanks in advance!

like image 385
TeeZee Avatar asked Oct 16 '25 13:10

TeeZee


2 Answers

You don't need to setup the call to UpdateRepository. Just verify it.

Given these types:

public interface IRepository
{
   void UpdateRepository(string value);
}

public class Service
{
    public Service(IRepository repository)
    {
        _repository = repository;
    }

    public void DoUpdate(string value)
    {
        _repository.UpdateRepository(value);
    }

    private IRepository _repository;
}

Your test method could be as follows:

const string param1 = "whatever";

var repoMock = new Mock<IRepository>();

var sut = new Service(repoMock.Object);

sut.DoUpdate(param1);

repoMock.Verify(x => x.UpdateRepository(param1), Times.Once());
like image 76
TrueWill Avatar answered Oct 19 '25 12:10

TrueWill


Try using Verifiable:

mock.Setup(m => m.UpdateRepository(param1)).Verifiable();
like image 43
Bassam Mehanni Avatar answered Oct 19 '25 11:10

Bassam Mehanni



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!