Home > front end >  mock Url.Action => returning null
mock Url.Action => returning null

Time:11-12

I have the following problem:

In a MVC application, Blazor, I have a controller with many methods. I am trying to test one of the methods, but after a few calls to other objects, it goes back to its controller calling a different method. This last method has the following line

Return Redirect(Url.Action("MyActionName", "MyControllerName", new { id = myId }));

At the beginning my problem was that Url was null, however, I sorted that with the following code in my test:

    var UrlHelperMock = new Mock<System.Web.Mvc.UrlHelper>();

    c.Url = UrlHelperMock.Object;

    UrlHelperMock.Setup(x => x.Action("MyActionName", "MyControllerName", new { id =  MyId })).Returns("myURL"   myId.ToString());

Now, Url is not null anymore, but when I try to see what Url.Action returns is null instead of "myURL" myId.ToString(). Any ideas on how to fix this, please?

CodePudding user response:

What I think is happening that the parameter new { id = MyId } is not equal to your setup because it is a reference type. Try doing the setup using the following code:

UrlHelperMock
    .Setup(x => x.Action("MyActionName", "MyControllerName", It.Is<T>(y => y.id == MyId )))
    .Returns("myURL"   myId.ToString());
//where T equals the type of the parameter

That will check if the parameter is the type T and whether the id of it equals your MyId.

CodePudding user response:

what it sorted for me was realizing that id needs to be just anything, so doing instead:

UrlHelperMock.Setup(x => x.Action("MyActionName", "MyControllerName", It.IsAny<object>() })).Returns("myURL"   myId.ToString());

Giving it as a gener T was erroring as it needed to be specific, and string didn't work either because there is no string.id, same for other types.

  • Related