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?
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With