I'm using Moq for unit testing. I want to mock a Guid
. I found this post about mocking Guid.NewGuid()
, but I don't know if it will work for me because I don't know (and can't find) what type mockGuidService
is.
-
2*Why* do you want to mock a `Guid`? What does your code look like? – Julian Aug 05 '16 at 20:14
2 Answers
You can implement a wrapper class with an interface, like this.
public interface IGuidService { Guid NewGuid(); }
class GuidService : IGuidService
{
public Guid NewGuid() { return Guid.NewGuid(); }
}
You'll have to add dependency injection to get this into your class. In the class you're testing, add an instance of the wrapper and assign it in a constructor.
class MyClass {
private IGuidService myGuidService;
public MyClass() { myGuidService = new GuidService(); }
public MyClass(IGuidService gw) { myGuidService = gw; }
public void DoSomethingThatRequiresAGuid() {
myGuidService.NewGuid();
}
}
Then in your tests, you'll do this:
var mockGuidService = new Mock<IGuidService>();
mockGuidService.Setup(x => x.NewGuid()).Returns( [a Guid of your choice] );
new MyClass(mockGuidService.Object);

- 31
- 2
-
This could solve the problem but it's quite disappointed to create a class to wrap around Guid as Guid is a struct – cscmh99 Jun 29 '20 at 07:55
mockGuidService
's type is Mock<IGuidService>
. It will only work if you are using an interface for your GUID providing service and you are able to inject the mock.
If your architecture is too tightly coupled to do that (no interfaces, no DI) then I would recommend to improve it, but if you just can't change it then there is an alternative. You can extract generating the GUID as method, mark it as virtual and create mock of the whole object in which you change the behaviour of the method.

- 467
- 5
- 11
-
Ah, it looks like that is Java. I'm using C#. Thank for such a fast answer though! – jenjer Aug 05 '16 at 20:01
-
@jenjer I am a little bit confused. Moq is for C# (https://github.com/moq/moq4) and I did write about using it. – gdziadkiewicz Aug 05 '16 at 20:04
-
-
2@Alok To be exact `It.IsAny
()` can be used during setup of a mock if you need to override a method accepting `Guid` as an argument. I believe that this is not the case for @jenjer . Most likely he used hardcoded `Guid.NewId()` calls in his code and hoped to be able to mock them somehow for unit testing purposes. – gdziadkiewicz Aug 11 '16 at 08:55