gpt4 book ai didi

c# - 如何使用 asp.net core 2 测试具有属性的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 12:23:02 25 4
gpt4 key购买 nike

我的项目是一个 ASP.NET Core 2.0 网络应用程序。

如何通过调用包含该属性的方法来测试我自己编写的属性是否正常工作?

例如:

属性

[AttributeUsage(AttributeTargets.Method)]
public class ValidateUserLoggedInAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var controller = (BaseController)context.Controller;
if (!controller.UserRepository.IsUserLoggedIn)
{
var routeValueForLogin = new RouteValueDictionary(new { action = "Login", controller = "Home", area = "" });
context.Result = new RedirectToRouteResult(routeValueForLogin);
}
}
}

Controller :

[ValidateUserLoggedIn]
public IActionResult Start()
{
...
}

测试:

[TestMethod]
public void Test()
{
// Act
var result = this.controllerUnderTest.Start() as RedirectToRouteResult;

// Assert
Assert.IsNotNull(result);
Assert.IsFalse(result.Permanent);

var routeValues = result.RouteValues;

const string ControllerKey = "controller";
Assert.IsTrue(routeValues.ContainsKey(ControllerKey));
Assert.AreEqual("Home", routeValues[ControllerKey]);

const string ActionKey = "action";
Assert.IsTrue(routeValues.ContainsKey(ActionKey));
Assert.AreEqual("Login", routeValues[ActionKey]);
}

我已经通过创建一个 ActionExecutingContext 只为属性编写了一个测试,但我还想为 Controller 方法测试它。

最佳答案

这将需要一个集成测试,您可以在其中使用内存中的测试服务器或正在运行的站点发送实际请求,然后验证预期的行为。

引用Integration testing in ASP.NET Core

您已经通过单元测试单独测试了该属性,如果测试涵盖了预期的行为,那么它在集成和生产中的行为将按预期进行,这是理所当然的

关于c# - 如何使用 asp.net core 2 测试具有属性的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428353/

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