gpt4 book ai didi

c# - 模拟方法以返回某些参数并为所有其他参数抛出异常

转载 作者:行者123 更新时间:2023-11-30 14:27:26 25 4
gpt4 key购买 nike

我正在使用 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...

我该怎么做?

最佳答案

为此您可以使用 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();

关于c# - 模拟方法以返回某些参数并为所有其他参数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32825990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com