模拟一个返回某些参数的方法,并抛出所有其他参数的异常

时间:2015-09-28 14:53:41

标签: c# moq

我使用Moq来模拟方法:

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

我想嘲笑这个,如果我传递这三个guid,它会返回记录,而所有其他Guid 会抛出异常。

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...

我该怎么做?

3 个答案:

答案 0 :(得分:4)

您可以使用MockBehavior.Strict

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();

答案 1 :(得分:2)

以下代码可以解决这个问题:

mock.Setup(t => t.GetRecord(It.Is<Guid>(q => q != id && q != id2 && q != id3)))
.Throws(new Exception("Bad Guid"));

答案 2 :(得分:0)

实际上这很容易:

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);