Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a method to return for some parameters and throws exception for all other parameters

Tags:

c#

moq

I am using Moq to mock a method:

public class DbService : IDbService
{
    public Record GetRecord(Guid Id)
    {
        // Returns the record if exists.
        // Throws exception if record not found.
    }
}

I want to mock this such that if I pass these three guids, it returns the records and for all other Guids throws an exception.

Guid id = Guid.NewGuid();
Guid id2 = Guid.NewGuid();
Guid id3 = Guid.NwGuid();

var mock = new Mock<IDbService>();
mock.Setup(t => t.GetRecord(id)).Returns(record1);
mock.Setup(t => t.GetRecord(id2)).Returns(record2);
mock.Setup(t => t.GetRecord(id3)).Returns(record3);
// Throw exception for all other guids...

How can I do this?

like image 249
A-Sharabiani Avatar asked Oct 18 '25 13:10

A-Sharabiani


2 Answers

Actually that was so easy:

mock.Setup(t => t.GetRecord(It.IsAny<Guid>())).Throws(new MyException());
mock.Setup(t => t.GetRecord(id)).Returns(record1);
mock.Setup(t => t.GetRecord(id2)).Returns(record2);
mock.Setup(t => t.GetRecord(id3)).Returns(record3);
like image 121
A-Sharabiani Avatar answered Oct 20 '25 02:10

A-Sharabiani


You can use MockBehavior.Strict for this:

Guid id = Guid.NewGuid();
Guid id2 = Guid.NewGuid();
Guid id3 = Guid.NwGuid();

var mock = new Mock<IDbService>(MockBehavior.Strict);

mock.Setup(t => t.GetRecord(id)).Returns(record1);
mock.Setup(t => t.GetRecord(id2)).Returns(record2);
mock.Setup(t => t.GetRecord(id3)).Returns(record3);

// do stuff

// will throw if GetRecord was called with arguments
// that don't match to any configured setup.
mock.VerifyAll();
like image 44
takemyoxygen Avatar answered Oct 20 '25 02:10

takemyoxygen



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!