Mocking Guid.NewGuid()

后端 未结 2 509
天涯浪人
天涯浪人 2021-01-18 02:02

Suppose I have the following entity:

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


        
相关标签:
2条回答
  • 2021-01-18 02:38

    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.

    0 讨论(0)
  • 2021-01-18 02:43

    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];
        }
    }
    
    0 讨论(0)
提交回复
热议问题