Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test HtmlHelper with Moq?

Could somebody show me how you would go about creating a mock HTML Helper with Moq?

This article has a link to an article claiming to describe this, but following the link only returns an ASP.NET Runtime Error

[edit] I asked a more specific question related to the same subject here, but it hasn't gotten any responses. I figured it was too specific, so I thought I could get a more general answer to a more general question and modify it to meet my requirements.

Thanks

like image 481
DaveDev Avatar asked Mar 22 '10 21:03

DaveDev


People also ask

What can be mocked with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

What is Moq in unit testing C#?

Moq is a mock object framework for . NET that greatly simplifies the creation of mock objects for unit testing. Mocking is a popular technique for unit testing that creates test double objects, which gives you the ability to control the behavior of those objects by setting their outcomes.

Is Moq a testing framework?

The Moq framework is an open source unit testing framework that works very well with .

What is xUnit and Moq?

Moq and xUnit belong to "Testing Frameworks" category of the tech stack. xUnit is an open source tool with 2.62K GitHub stars and 610 GitHub forks. Here's a link to xUnit's open source repository on GitHub.


1 Answers

Here's another article that shows you how to achieve the same thing:

public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd) {   var mockViewContext = new Mock<ViewContext>(     new ControllerContext(       new Mock<HttpContextBase>().Object,       new RouteData(),       new Mock<ControllerBase>().Object),     new Mock<IView>().Object,     vd,     new TempDataDictionary());    var mockViewDataContainer = new Mock<IViewDataContainer>();   mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);    return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object); } 
like image 67
Thomas Avatar answered Sep 29 '22 01:09

Thomas