I am currently having issues with testing a method which my controller uses which is mocked. it has a return type of an specific enum. I am currently always getting back from this mocked method the default enum value, not the value that I have specified it to return. Am i missing something? I have tried both Moq and JustMock lite with the same results. JustMock lite example below.
Hopefully i haven't made any mistakes in copying the code, I have changed all the names of the objects so apologies for that.
Here is part the unit test:
var returnStatus = ExampleEnum.Invalid;
//Mock the client
var client = Mock.Create<ITestInterface>();
Mock.Arrange(() => client.ValidateSomething(Guid.NewGuid()))
.Returns(returnStatus).MustBeCalled();
var testController = new TestController(client);
var result = testController.DoSomething(Guid.NewGuid().ToString()) as ViewResult;
Here are the relevant bits from the controller:
private ITestInterface _client { get; set; }
public TestController(ITestInterface client)
{
_client = client;
}
Here is part of my controller action:
public ActionResult DoSomething(string id)
{
Guid token;
if(!string.IsNullOrEmpty(id) && Guid.TryParse(id, out token))
{
using (var client = _client)
{
ApplicationUser applicationUser;
var status = client.ValidateSomething(token);
switch (status)
{
The client is mocked correctly but the "status" property getting returned is always ExampleEnum.DefaultValue not the value i have specified to be the result.
I hope i have provided enough information. Any help much appreciated.
You probably did your setup wrong.
Guid.NewGuid()
returns a new random GUID, so the GUID you use to setup your mock and the GUID you use to call the DoSomething
method will never be the same.
You should do something like:
var guid = Guid.NewGuid()
...
Mock.Arrange(() => client.ValidateSomething(guid))
.Returns(returnStatus).MustBeCalled();
...
var result = testController.DoSomething(guid.ToString()) as ViewResult;
using the same GUID for the mock and for the call to DoSomething
.
I don't know about JustMock, but with Moq you could also simply use It.IsAny
to match all GUIDs:
client.Setup(c => c.ValidateSomething(It.IsAny<Guid>())).Returns(returnStatus);