gpt4 book ai didi

c# - 在 ServiceStack 中是否可以模拟 Request.OriginalRequest 对象进行单元测试?

转载 作者:太空狗 更新时间:2023-10-29 21:09:29 28 4
gpt4 key购买 nike

我想让我的 ServiceStack 服务可测试。

目前我有:

[RequireFormsAuthentication]
public object Delete(DeleteRequest request)
{
var originalRequest = (HttpRequest)Request.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
return othercode(identity);
}

RequireFormsAuthentication 在哪里

public class RequireFormsAuthenticationAttribute : RequestFilterAttribute
{
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var originalRequest = (HttpRequest)req.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
if (!identity.IsAuthenticated)
{
res.StatusCode = (int)HttpStatusCode.Forbidden;
res.EndServiceStackRequest(skipHeaders: true);
}
}
}

我已经模拟了“othercode()”使用的所有依赖项,剩下的就是基类 Service 中的内容。是否有一种模式/策略/方法/我缺少的东西使这变得微不足道?

最佳答案

以下是如何使用最小起订量进行测试。此服务在查询字符串中查找“键”和“值”,并在请求 DTO 中查找另一个参数。该服务根据给定的值返回一个字符串响应。

    [Test]
public void MyTest()
{
var mockRequestContext = new Mock<IRequestContext>();
var mockedHttpRequest = new Mock<IHttpRequest>();

NameValueCollection querystring = new NameValueCollection();
querystring.Add("myKey", "myValue");

mockedHttpRequest.SetupGet(r => r.QueryString).Returns(querystring);

mockRequestContext.Setup(x => x.Get<IHttpRequest>()).Returns(mockedHttpRequest.Object);

AboutService service = new AboutService
{
RequestContext = mockRequestContext.Object,
};

AboutResponse response = (AboutResponse)service.Any(new About
{
Company = "myOtherValue",
});

Assert.AreEqual(0, response.QueryResult);
Assert.AreEqual("validResponse", response.Version);
}

关于c# - 在 ServiceStack 中是否可以模拟 Request.OriginalRequest 对象进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16218440/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com