模拟Guid.NewGuid() [英] Mocking Guid.NewGuid()

查看:90
本文介绍了模拟Guid.NewGuid()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下实体:

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

Part of the implementation should create two new GUIDs: one for UserGuid, and another for ConfirmationGuid. They should do this by setting the values to Guid.NewGuid().

我已经使用接口抽象了Guid.NewGuid():

I already have abstracted Guid.NewGuid() using an interface:

public interface IGuidService
{
    Guid NewGuid();
}

因此,当只需要一个新的GUID时,我可以轻松地对此进行模拟.但是我不确定如何从一个方法中模拟对同一方法的两个不同调用,以使它们返回不同的值.

So I can easily mock this when only one new GUID is needed. But I'm not sure how to mock two different calls to the same method, from within one method, such that they return different values.

推荐答案

如果您使用的是Moq,则可以使用:

If you are using Moq, you can use:

mockGuidService.SetupSequence(gs => gs.NewGuid())
    .Returns( ...some value here...)
    .Returns( ...another value here... );

我想您也可以执行以下操作:

I suppose you could also do the following:

mockGuidService.Setup(gs => gs.NewGuid())
    .Returns(() => ...compute a value here...);

不过,除非您只是在return函数中提供随机值,否则了解顺序仍然很重要.

Still, unless you are just supplying a random value within the return function, knowledge of order still seems to be important.

这篇关于模拟Guid.NewGuid()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆