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