gpt4 book ai didi

c# - 测试 MVC Controller 操作 HttpAcceptAttribute 动词

转载 作者:行者123 更新时间:2023-11-30 15:12:11 26 4
gpt4 key购买 nike

对 Controller 操作 HttpAcceptAttribute 动词进行单元测试的最佳方法是什么?

到目前为止,我有以下内容,但它太丑了,连妈妈都不喜欢,而且不太灵活。有没有更好的办法?

[Fact] // using xUnit, mocking controller in class
public void FilterControllerTestRemoveFilterByProductAttributeIsOfTypePost()
{
Type[] paramTypes = new[] { typeof(int) };
var method = typeof(FilterController).GetMethod("MyMethod", paramTypes);

var attributes = method.GetCustomAttributes(typeof(AcceptVerbsAttribute), false).Cast<AcceptVerbsAttribute>().SingleOrDefault();
Assert.NotNull(attributes);
Assert.Equal(1, attributes.Verbs.Count());
Assert.True(attributes.Verbs.First().Equals(HttpVerbs.Post.ToString(), StringComparison.InvariantCultureIgnoreCase));
}

谢谢麦克

最佳答案

没有反射和魔法字符串,在不破坏单元测试的情况下很容易重命名 Controller 和方法:

[TestMethod]
public void HomeController_Index_Action_Should_Accept_Post_Verb_Only()
{
Expression<Action<HomeController>> expression = (HomeController c) => c.Index(null);
var methodCall = expression.Body as MethodCallExpression;
var acceptVerbs = (AcceptVerbsAttribute[])methodCall.Method.GetCustomAttributes(typeof(AcceptVerbsAttribute), false);
acceptVerbs.ShouldNotBeNull("");
acceptVerbs.Length.ShouldBe(1);
acceptVerbs[0].Verbs.First().ShouldBe("POST");
}

关于c# - 测试 MVC Controller 操作 HttpAcceptAttribute 动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583757/

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