Mocking Guid.NewGuid()

筅森魡賤 提交于 2019-12-01 16:52:40

问题


Suppose I have the following entity:

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public Guid UserGuid { get; set; }
    public Guid ConfirmationGuid { get; set; }
}

And the following interface method:

void CreateUser(string username);

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

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

public interface IGuidService
{
    Guid NewGuid();
}

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.


回答1:


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

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




回答2:


If you can't use Moq as in @Matt's example then you can build your own class which will do essentially the same thing.

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];
    }
}


来源:https://stackoverflow.com/questions/11589320/mocking-guid-newguid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!