How to Mock IUrlHelperHow do I calculate someone's age in C#?How do I test a private function or a class that has private methods, fields or inner classes?How do I enumerate an enum in C#?How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to loop through all enum values in C#?How to make mock to void methods with MockitoMock HttpContext.Current in Test Init MethodWhat is a NullReferenceException, and how do I fix it?How to mock the CreateResponse<T> extension method on HttpRequestMessage

Is it okay to submit a paper from a master's thesis without informing the advisor?

What will happen if I checked in for another room in the same hotel, but not for the booked one?

How do I ensure my employees don't abuse my flexible work hours policy?

Sacrifice blocking creature before damage is dealt no longer working (MtG Arena)?

Can I travel from Germany to England alone as an unaccompanied minor?

How Do I Know When I am in Private Mode?

Is it possible to have a character with proficiency in all martial weapons without proficiency in Medium armor?

How could a satellite follow earth around the sun while staying outside of earth's orbit?

Single level file directory

Bin Packing with Relational Penalization

How do I organize members in a struct to waste the least space on alignment?

How can a valley surrounded by mountains be fertile and rainy?

"Vector quantity" --More than two dimensions?

Using “ser” without "un/una"?

Is there a legal way for US presidents to extend their terms beyond two terms of four years?

Prime parity peregrination

I need help with pasta

Can European countries bypass the EU and make their own individual trade deal with the U.S.?

I hit a pipe with a mower and now it won't turn

Put my student loan in parents’ second mortgage - help?

How to describe POV characters?

Converting Geographic Coordinates into Lambert2008 coordinates

Is it okay to fade a human face just to create some space to place important content over it?

What are good ways to spray paint a QR code on a footpath?



How to Mock IUrlHelper


How do I calculate someone's age in C#?How do I test a private function or a class that has private methods, fields or inner classes?How do I enumerate an enum in C#?How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to loop through all enum values in C#?How to make mock to void methods with MockitoMock HttpContext.Current in Test Init MethodWhat is a NullReferenceException, and how do I fix it?How to mock the CreateResponse<T> extension method on HttpRequestMessage






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Getting started with Unit Tests can be frustrating, getting stuck at every detail. Hope this will improve as I gain more experience.



Now, how do I mock IUrlHelper for unit test?



I have this simple method to get absolute paths in ASP.NET



public static string AbsolutePage(this IUrlHelper url, string pageName, string pageHandler = null, object routeValues = null)

return url.Page(pageName, pageHandler, routeValues, url.ActionContext.HttpContext.Request.Scheme);



Mocking the Scheme is easy



return Mock.Of<IUrlHelper>(x =>
x.ActionContext.HttpContext.Request.Scheme == "http");


but then the method calls the Page method on the IUrlHelper. What do I do now?



I'd be tempted to skip small frustrating tests like this, but I think it's important to be vigorous when first learning.










share|improve this question



















  • 3





    actually, it's important to focus on what is important to test. you don't have to test and mock everything. Focus on the basics, get those right, then everything will fall into place. Test your own functionality, not frameworks

    – Andrei Dragotoniu
    Mar 25 at 14:20






  • 2





    @AndreiDragotoniu: is right. You're mostly testing the framework here. Extensions are very difficult to unit test, so the general idea is that they should be kept minimal and mostly just proxy to code that can/is thoroughly tested. Here, the only thing that could possibly go wrong is if you literally passed the parameters wrong to url.Page, which is mostly covered by compile-time checking. In short, there's no real need to test this method at all.

    – Chris Pratt
    Mar 25 at 14:38

















0















Getting started with Unit Tests can be frustrating, getting stuck at every detail. Hope this will improve as I gain more experience.



Now, how do I mock IUrlHelper for unit test?



I have this simple method to get absolute paths in ASP.NET



public static string AbsolutePage(this IUrlHelper url, string pageName, string pageHandler = null, object routeValues = null)

return url.Page(pageName, pageHandler, routeValues, url.ActionContext.HttpContext.Request.Scheme);



Mocking the Scheme is easy



return Mock.Of<IUrlHelper>(x =>
x.ActionContext.HttpContext.Request.Scheme == "http");


but then the method calls the Page method on the IUrlHelper. What do I do now?



I'd be tempted to skip small frustrating tests like this, but I think it's important to be vigorous when first learning.










share|improve this question



















  • 3





    actually, it's important to focus on what is important to test. you don't have to test and mock everything. Focus on the basics, get those right, then everything will fall into place. Test your own functionality, not frameworks

    – Andrei Dragotoniu
    Mar 25 at 14:20






  • 2





    @AndreiDragotoniu: is right. You're mostly testing the framework here. Extensions are very difficult to unit test, so the general idea is that they should be kept minimal and mostly just proxy to code that can/is thoroughly tested. Here, the only thing that could possibly go wrong is if you literally passed the parameters wrong to url.Page, which is mostly covered by compile-time checking. In short, there's no real need to test this method at all.

    – Chris Pratt
    Mar 25 at 14:38













0












0








0


1






Getting started with Unit Tests can be frustrating, getting stuck at every detail. Hope this will improve as I gain more experience.



Now, how do I mock IUrlHelper for unit test?



I have this simple method to get absolute paths in ASP.NET



public static string AbsolutePage(this IUrlHelper url, string pageName, string pageHandler = null, object routeValues = null)

return url.Page(pageName, pageHandler, routeValues, url.ActionContext.HttpContext.Request.Scheme);



Mocking the Scheme is easy



return Mock.Of<IUrlHelper>(x =>
x.ActionContext.HttpContext.Request.Scheme == "http");


but then the method calls the Page method on the IUrlHelper. What do I do now?



I'd be tempted to skip small frustrating tests like this, but I think it's important to be vigorous when first learning.










share|improve this question
















Getting started with Unit Tests can be frustrating, getting stuck at every detail. Hope this will improve as I gain more experience.



Now, how do I mock IUrlHelper for unit test?



I have this simple method to get absolute paths in ASP.NET



public static string AbsolutePage(this IUrlHelper url, string pageName, string pageHandler = null, object routeValues = null)

return url.Page(pageName, pageHandler, routeValues, url.ActionContext.HttpContext.Request.Scheme);



Mocking the Scheme is easy



return Mock.Of<IUrlHelper>(x =>
x.ActionContext.HttpContext.Request.Scheme == "http");


but then the method calls the Page method on the IUrlHelper. What do I do now?



I'd be tempted to skip small frustrating tests like this, but I think it's important to be vigorous when first learning.







c# .net asp.net-mvc unit-testing asp.net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 14:49









Johnny

4,8481 gold badge10 silver badges22 bronze badges




4,8481 gold badge10 silver badges22 bronze badges










asked Mar 25 at 14:15









Etienne CharlandEtienne Charland

6681 gold badge4 silver badges23 bronze badges




6681 gold badge4 silver badges23 bronze badges







  • 3





    actually, it's important to focus on what is important to test. you don't have to test and mock everything. Focus on the basics, get those right, then everything will fall into place. Test your own functionality, not frameworks

    – Andrei Dragotoniu
    Mar 25 at 14:20






  • 2





    @AndreiDragotoniu: is right. You're mostly testing the framework here. Extensions are very difficult to unit test, so the general idea is that they should be kept minimal and mostly just proxy to code that can/is thoroughly tested. Here, the only thing that could possibly go wrong is if you literally passed the parameters wrong to url.Page, which is mostly covered by compile-time checking. In short, there's no real need to test this method at all.

    – Chris Pratt
    Mar 25 at 14:38












  • 3





    actually, it's important to focus on what is important to test. you don't have to test and mock everything. Focus on the basics, get those right, then everything will fall into place. Test your own functionality, not frameworks

    – Andrei Dragotoniu
    Mar 25 at 14:20






  • 2





    @AndreiDragotoniu: is right. You're mostly testing the framework here. Extensions are very difficult to unit test, so the general idea is that they should be kept minimal and mostly just proxy to code that can/is thoroughly tested. Here, the only thing that could possibly go wrong is if you literally passed the parameters wrong to url.Page, which is mostly covered by compile-time checking. In short, there's no real need to test this method at all.

    – Chris Pratt
    Mar 25 at 14:38







3




3





actually, it's important to focus on what is important to test. you don't have to test and mock everything. Focus on the basics, get those right, then everything will fall into place. Test your own functionality, not frameworks

– Andrei Dragotoniu
Mar 25 at 14:20





actually, it's important to focus on what is important to test. you don't have to test and mock everything. Focus on the basics, get those right, then everything will fall into place. Test your own functionality, not frameworks

– Andrei Dragotoniu
Mar 25 at 14:20




2




2





@AndreiDragotoniu: is right. You're mostly testing the framework here. Extensions are very difficult to unit test, so the general idea is that they should be kept minimal and mostly just proxy to code that can/is thoroughly tested. Here, the only thing that could possibly go wrong is if you literally passed the parameters wrong to url.Page, which is mostly covered by compile-time checking. In short, there's no real need to test this method at all.

– Chris Pratt
Mar 25 at 14:38





@AndreiDragotoniu: is right. You're mostly testing the framework here. Extensions are very difficult to unit test, so the general idea is that they should be kept minimal and mostly just proxy to code that can/is thoroughly tested. Here, the only thing that could possibly go wrong is if you literally passed the parameters wrong to url.Page, which is mostly covered by compile-time checking. In short, there's no real need to test this method at all.

– Chris Pratt
Mar 25 at 14:38












1 Answer
1






active

oldest

votes


















-1














If you still want to test your IUrlHelper you may use this code



var mocked = new Mock<IUrlHelper>();

mocked.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<string>()))
.Returns("whatever_string");

IUrlHelper helper = mocked.Object;





share|improve this answer























  • Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

    – Etienne Charland
    Mar 25 at 15:02












  • I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

    – Etienne Charland
    May 13 at 5:23










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55339855%2fhow-to-mock-iurlhelper%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









-1














If you still want to test your IUrlHelper you may use this code



var mocked = new Mock<IUrlHelper>();

mocked.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<string>()))
.Returns("whatever_string");

IUrlHelper helper = mocked.Object;





share|improve this answer























  • Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

    – Etienne Charland
    Mar 25 at 15:02












  • I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

    – Etienne Charland
    May 13 at 5:23















-1














If you still want to test your IUrlHelper you may use this code



var mocked = new Mock<IUrlHelper>();

mocked.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<string>()))
.Returns("whatever_string");

IUrlHelper helper = mocked.Object;





share|improve this answer























  • Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

    – Etienne Charland
    Mar 25 at 15:02












  • I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

    – Etienne Charland
    May 13 at 5:23













-1












-1








-1







If you still want to test your IUrlHelper you may use this code



var mocked = new Mock<IUrlHelper>();

mocked.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<string>()))
.Returns("whatever_string");

IUrlHelper helper = mocked.Object;





share|improve this answer













If you still want to test your IUrlHelper you may use this code



var mocked = new Mock<IUrlHelper>();

mocked.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<string>()))
.Returns("whatever_string");

IUrlHelper helper = mocked.Object;






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 25 at 14:38









xnegxneg

4614 silver badges12 bronze badges




4614 silver badges12 bronze badges












  • Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

    – Etienne Charland
    Mar 25 at 15:02












  • I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

    – Etienne Charland
    May 13 at 5:23

















  • Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

    – Etienne Charland
    Mar 25 at 15:02












  • I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

    – Etienne Charland
    May 13 at 5:23
















Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

– Etienne Charland
Mar 25 at 15:02






Ya. That would test that Page gets called; but not that it's generating the expected absolute URLs in a variety of scenarios, so the test would be of limited use really. And since the inner-working of the function is a bit complex, I can't say it works until I run it. And the fact that it uses the UrlHelper to generate the absolute URLs is an internal matter that ideally the test wouldn't care about -- as long as it provides the expected result.

– Etienne Charland
Mar 25 at 15:02














I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

– Etienne Charland
May 13 at 5:23





I found back this post after bumping into the same issue again. Page is an extension method in UrlHelperExtensions and not a member of IUrlHelper, thus it can't be mocked in that way.

– Etienne Charland
May 13 at 5:23








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55339855%2fhow-to-mock-iurlhelper%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현