Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Guid.NewGuid()

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.

like image 754
Jerad Rose Avatar asked Jul 21 '12 03:07

Jerad Rose


1 Answers

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.

like image 165
Matt H Avatar answered Sep 19 '22 02:09

Matt H