Mocking Guid.NewGuid()

旧城冷巷雨未停 提交于 2019-12-01 16:46:29

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.

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