0

I have following asp.net Page Contact and having TestHandlerDemoClass which is having one method I want to write a unit test case for that method but when I tried it using MSTest project it throws exception like Request not available in this context

public partial class Contact : Page
    {

    }
 public class TestHandlerDemoClass
    {
 public void MyTestMethod(Page mypage)
        {
       string id= mypage.Request["EntityId"]

//here I'm not getting Request inside mypage 

My Test Project code -

[TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void NullCheck()
        {
            try
            {
                Contact contactPage = new Contact();
                TestHandlerDemoClass mydemo = new TestHandlerDemoClass();
                mydemo.MyTestMethod(contactPage);
            }
            catch (Exception ex)
            {
                Assert.AreEqual(ex.Message, "Id not found");
            }
        }
    }

here in above ex I got message like {"Request is not available in this context"}

I 'm just trying to write unit test cases for method `

public void MyTestMethod(Page mypage)

which takes Page mypage as parameter.

how to do it?

Neo
  • 15,491
  • 59
  • 215
  • 405

2 Answers2

1

By mocking your Contact class the test will pass, the problem is most of the unit testing tools doesn't allow to mock a Non-virtual Class. im using Typemock where its possible to mock almost any type of Object without changing your code, and its realy esay to use.

for example:

  [TestMethod]
        public void NullCheck()
        {
            try
            {
                var contactPage = Isolate.Fake.Instance<Contact>();
                TestHandlerDemoClass t = new TestHandlerDemoClass();
                t.MyTestMethod(contactPage);
            }
            catch (Exception ex)
            {
                Assert.AreEqual(ex.Message, "Id not found");
            }
        }
Gregory Prescott
  • 574
  • 3
  • 10
0

I'm not an expert in unit testing, but I think you should pass a mock object like is answered here: How to mock the Request on Controller in ASP.Net MVC?

Community
  • 1
  • 1
Kraviec
  • 13
  • 1
  • 6
  • I got your point thanks but instead of mock it would be more simpler if I got to know how to pass a page request from unit test method – Neo Nov 05 '16 at 11:12
  • An [HttpRequest object](https://msdn.microsoft.com/it-it/library/system.web.httprequest(v=vs.110).aspx) is something quite complicated, that is build starting from what is sent by a client able to send http request (often, a browser). I doubt you can find something simpler than a mock – Gian Paolo Nov 05 '16 at 11:58
  • how to mock for asp.net instead of controller as my method is having Page as input? – Neo Nov 05 '16 at 18:44