单元测试 AjaxRequest C#
本文关键字:AjaxRequest 单元测试 | 更新日期: 2023-09-27 18:37:16
[Test]
public void DetailPromocodeStatusWithModel()
{
var sut = _testContext.Sut;
_httpModelFactory.FakeHttpContext();
var mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
var mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
mockHttpContext.Stub(x => x.Request).Return(mockRequest);
mockRequest.Stub(x => x.HttpMethod).Return("POST");
var context = new ControllerContext(mockHttpContext,new RouteData(),sut);
sut.ControllerContext = context;
var viewResult = sut.Enquire(SampleEnquiryForm());
Debug.Assert(viewResult != null, "view != null");
Assert.NotNull(viewResult);
}
*我正在对一个具有特定 IF 语句的类进行单元测试,该语句要求我的请求为 POST 并且 isAjaxRequest 为真才能进入特定块。我已经设置了 POST 部分,但我似乎无法设置标头以使其成为 AJAX 请求,而不会失败。*
对于单元测试,你可以模拟isAjaxRequest()方法进入所需的块。就个人而言,我使用Typemock隔离器来实现此类目的,因为它允许模拟静态方法。看一看:
[TestMethod, Isolated]
public void TestIsAjaxRequest()
{
var fake = Isolate.Fake.Instance<HttpRequestBase>();
Isolate.WhenCalled(() => AjaxRequestExtensions.IsAjaxRequest(null)).WillReturn(true);
Assert.IsTrue(AjaxRequestExtensions.IsAjaxRequest(fake));
}
希望对您有所帮助。