假设我有以下实体:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public Guid UserGuid { get; set; }
public Guid ConfirmationGuid { get; set; }
}
以下界面方法:
void CreateUser(string username);
部分实施应创建两个新GUID:一个用于UserGuid
,另一个用于ConfirmationGuid
。他们应该通过将值设置为Guid.NewGuid()
来完成此操作。
我已经使用界面抽象了Guid.NewGuid():
public interface IGuidService
{
Guid NewGuid();
}
因此,当只需要一个新的GUID时,我可以轻松地模拟它。但是我不确定如何在一个方法中模拟对同一方法的两个不同的调用,以便它们返回不同的值。
答案 0 :(得分:10)
如果您使用Moq,可以使用:
mockGuidService.SetupSequence(gs => gs.NewGuid())
.Returns( ...some value here...)
.Returns( ...another value here... );
我想你也可以做以下事情:
mockGuidService.Setup(gs => gs.NewGuid())
.Returns(() => ...compute a value here...);
尽管如此,除非您只是在返回函数中提供随机值,否则对顺序的了解似乎仍然很重要。
答案 1 :(得分:4)
如果你不能在@ Matt的例子中使用Moq,那么你可以构建自己的类,这将基本上做同样的事情。
public class GuidSequenceMocker
{
private readonly IList<Guid> _guidSequence = new[]
{
new Guid("{CF0A8C1C-F2D0-41A1-A12C-53D9BE513A1C}"),
new Guid("{75CC87A6-EF71-491C-BECE-CA3C5FE1DB94}"),
new Guid("{E471131F-60C0-46F6-A980-11A37BE97473}"),
new Guid("{48D9AEA3-FDF6-46EE-A0D7-DFCC64D7FCEC}"),
new Guid("{219BEE77-DD22-4116-B862-9A905C400FEB}")
};
private int _counter = -1;
public Guid Next()
{
_counter++;
// add in logic here to avoid IndexOutOfRangeException
return _guidSequence[_counter];
}
}