Mocking Guid.NewGuid ()

Suppose I have the following object:

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 is to create two new GUIDs: one for UserGuidand one for ConfirmationGuid. They must do this by setting values Guid.NewGuid().

I have already rendered Guid.NewGuid () using the interface:

public interface IGuidService
{
    Guid NewGuid();
}

Therefore, I can easily make fun of it when only one new GUID is needed. But I'm not sure how to mock two different calls of the same method from the same method so that they return different values.

+5
source share
2 answers

If you use Moq, you can use:

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

Suppose you can also do the following:

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

, , .

+9

Moq, @Matt, , .

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

All Articles