3
我有一個控制器,它走的是智威湯遜索賠,如果索賠是正確的,那麼我returing類別的JSON字符串如下: -集成測試與.NET的核心和NUnit
[Authorize(Policy = "OnlyValidUsers")]
[Route("api/[controller]")]
public class CategoriesController : Controller
{
private readonly IGenericService<Category> _categoriesService;
public CategoriesController(IGenericService<Category> categoriesService)
{
_categoriesService = categoriesService;
}
[Authorize(Policy = "GenericUser")]
[HttpGet("/api/Categories/Get", Name = "GetCategories")]
public async Task<IActionResult> Get()
{
var categories = await _categoriesService.GetAll();
return Json(categories);
}
}
這在用戶登錄到我的系統後發生,並獲得不記名令牌。
我試圖測試在集成測試如下: -
[TestFixture]
public class CategoriesControllerIntegrationTests
{
private HttpClient _client;
private Category _testCategory;
private string _request;
[SetUp]
public void Setup()
{
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var projectPath = Path.GetFullPath(Path.Combine(basePath, "../../../../SportsStore.Tests"));
var server = new TestServer(Utils.GetHostBuilder(new string[] { })
.UseContentRoot(projectPath)
.UseEnvironment("Development")
.UseStartup<Startup>());
_client = server.CreateClient();
_testCategory = new Category
{
Name = Enums.GetEnumDescription(Enums.CategoryTestData.Name)
};
_request = Enums.GetEnumDescription(Enums.Requests.Categories);
}
[Test]
public async Task Get_ReturnsAListOfCategories_CategoriesController()
{
var response = await _client.GetAsync(_request + "Get");
response.EnsureSuccessStatusCode();
Assert.IsTrue(true);
}
的utils的類如下: -
public class Utils
{
public static IWebHostBuilder GetHostBuilder(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
return new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
}
}
當我運行測試,我得到一個預計401(未授權)。我怎樣才能通過這個考試?我如何在測試中通過索賠來驗證其工作?
此外,如果我刪除[授權]過濾器,我仍然得到401(未授權),我認爲不應該發生。
任何幫助將不勝感激!
感謝
您是否刪除了兩個'Authrize'過濾器,因爲我看到它們中的2個(並且您是否更詳細地指定爲全局過濾器)?請確保您通過提供正確的Cookie狀態(例如首先登錄)或者在策略中覆蓋(但可能會在稍後使您易受攻擊),將授權屬性與測試一起傳遞。 –
我以前刪除它們只是爲了檢查這些是否是原因,但是當我刪除它們時,我仍然有401,這就是爲什麼我懷疑我在Setup.cs中有什麼問題或TestServer – Johann
證實該問題是這樣的services.AddMvc(配置=> { 變種政策=新AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(新AuthorizeFilter(策略)); }); – Johann