[英]Testing routes in a .NET Core Web application
我正在嘗試編寫一組測試,以確認預期的路由將轉到正確的Controllers / Actions。
我通過查看其他地方的示例來完成其中的一部分,但是現在我不知道如何(或是否有可能)從可用的對象中獲取控制器詳細信息。
[Test]
public void Test_A_Route()
{
var server = new TestServer(
new WebHostBuilder()
.UseEnvironment("Development")
.UseConfiguration(GetConfiguration())
.UseStartup<Startup>());
var client = server.CreateClient();
var response = client.GetAsync("/My/Url/").GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
string contentResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
contentResult.Should().Contain("Some text from my webpage that is hopefully unique");
}
我希望能夠驗證以下內容:
任何想法如何去做?
為了獲得控制器的詳細信息,我建議您使用Flurl 。 如您在此處和下方的項目文檔中所見,您可以按以下方式聲明控制器的詳細信息。 據我了解,該庫偽造了HttpClient,並且可以通過單元測試的方式來獲取控制器方法的詳細信息。 我認為這個項目非常可行,希望對您有所幫助。
// fake & record all http calls in the test subject
using (var httpTest = new HttpTest()) {
// arrange
httpTest.RespondWith(200, "OK");
// act
await yourController.CreatePersonAsync();
// assert
httpTest.ShouldHaveCalled("https://api.com/*")
.WithVerb(HttpMethod.Post)
.WithContentType("application/json");
}
我認為您可以將此IActionFilter用於此任務:
public class DebugFilter : IActionFilter
{
bool enabled = false;
IDictionary<string, object> arguments = null;
public void OnActionExecuting(ActionExecutingContext context)
{
enabled = context.HttpContext.Request.Headers.ContainsKey("X-Debug");
if (enabled)
{
arguments = context.ActionArguments;
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
if (enabled)
{
var controllerName = context.Controller.GetType().Name;
var actionName = context.ActionDescriptor.DisplayName;
context.HttpContext.Response.Headers.Add("X-Controller-Name", controllerName);
context.HttpContext.Response.Headers.Add("X-Action-Name", actionName);
context.HttpContext.Response.Headers.Add("X-Action-Model", JsonConvert.SerializeObject(arguments));
}
}
}
並將其全局注冊到您的Startup.cs文件中:
#if DEBUG
services.AddMvc(options =>
{
options.Filters.Add(new DebugFilter());
})
#else
services.AddMvc()
#endif
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
之后,您僅在測試中包括“ X-Debug”標頭,並從響應標頭接收您想要的所有信息。
編輯:這是ofc非常簡單的類,您可以訪問ViewData,Result,TempData等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.