如何模拟 ASP.Net WebForm 页面的请求?

How to mock the Request for ASP.Net WebForm Page?

我关注 asp.net 页面 Contact 并且 TestHandlerDemoClass 有一种方法我想为该方法编写一个单元测试用例但是当我尝试使用 MSTest project 它会抛出异常 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 

我的测试项目代码 -

[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");
            }
        }
    }

在上面的例子中,我收到了类似 {"Request is not available in this context"}

的消息

我只是想为方法 `

编写单元测试用例
public void MyTestMethod(Page mypage)

Page mypage为参数。

怎么做?

我不是单元测试方面的专家,但我认为你应该传递一个模拟对象就像这里的回答:How to mock the Request on Controller in ASP.Net MVC?

通过模拟您的 Contact class 测试将通过,问题是大多数单元测试工具不允许模拟非虚拟 Class。 我正在使用 Typemock,它可以在不更改代码的情况下模拟几乎任何类型的对象,而且它真的很容易使用。

例如:

  [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");
            }
        }