gpt4 book ai didi

c# - 如何在 nunit dotnet 核心测试项目中使用 appsettings?

转载 作者:行者123 更新时间:2023-11-30 20:33:35 25 4
gpt4 key购买 nike

我已经设法从 appsettings.json 文件中将 AppSettings 添加到我的 Api 项目中

ConfigureServices() 函数中的 Startup.cs

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

Controller .cs

private readonly AppSettings _AppSettings;

public UserProfilesController(IOptions<AppSettings> appSettings)
{
_AppSettings = appSettings.Value;
}

但我不知道如何为我的测试项目执行此操作。我的测试项目中没有 Startup.ts。那么如何在我的测试项目中以相同的方式添加应用程序设置呢?

编辑:

一个nunit测试

    [Test]
public void Post_Should_Create_A_Single_UserProfile()
{
// Arrange
var profile = Dummy.GenerateCreateUserProfileDto();

MyMvc
.Controller<UserProfilesController>()
.Calling(c => c.Post(profile))
.ShouldReturn()
.Ok()
.WithResponseModelOfType<UserProfileDto>()
.Passing(target =>
{
target.Should().NotBeNull(because: "a record is expected here");
target.Id.Should().BeGreaterThan(0, because: "a id is expected");
target.ShouldBeEquivalentTo(profile, opt => opt
.Excluding(c => c.Id)
.Excluding(c => c.CreatedOn)
.Excluding(c => c.ModifiedOn),
because: "the record returned is expected to be the same as the record inserted");

// Clean up
_Repo.Delete(target.Id);
});
}

我的帖子功能

    [HttpPost]
public async Task<IActionResult> Post([FromBody]CreateUserProfileDto profile)
{
using (var fileManager = new FileManager())
using (var manager = new UserProfilesRepository())
{
var mapped = Mapper.Map<UserProfile>(profile);
// Only save the profile image if one is selected
if (!string.IsNullOrEmpty(profile.Image))
{
try
{
var result = fileManager.SaveProfileImage(
profile.Image,
_AppSettings.Profile.AbsolutePath,
_AppSettings.BaseUrl,
_AppSettings.Profile.RelativePath
);
mapped.FilePath = result.AbsolutePath;
mapped.ProfilePicture = result.RelativePath;
}
catch (Exception ex)
{
return StatusCode(500);
}
}

manager.Save(mapped);

return Ok(Mapper.Map<UserProfileDto>(mapped));
}
}

最佳答案

您正在模拟您的 MVC Controller 来测试它。这样,您应该通过模拟的 appSettings 对象创建您的 UserProfilesController

另一种选择是启动应用程序以使用 Startup.cs 类对其进行测试。我从未使用过 nUnit,但在 xUnit 中我这样配置我的测试项目:

TestServer testServer = new TestServer(new WebHostBuilder().UseEnvironment("Development").UseStartup<Startup>());

由于我使用的是Development 环境,因此我的测试项目中还需要一个appsettings.Development.json 文件。

然后,您可以像这样使用您创建的内存服务器:

testServer.CreateClient().PostAsync(string requestUri, HttpContent content)

编辑:

TestServer 来自微软包:

"Microsoft.AspNetCore.TestHost": "1.0.0"

因此,它应该可以与 nUnit 一起正常工作。

关于c# - 如何在 nunit dotnet 核心测试项目中使用 appsettings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40093898/

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