gpt4 book ai didi

c# - 使用 asp.net core 进行集成测试(没有 View 的 Controller 测试)

转载 作者:行者123 更新时间:2023-11-28 20:48:03 25 4
gpt4 key购买 nike

我正在尝试设置一个测试项目来测试我的 Controller 和数据库,而无需定义 View 。

我有一个单元测试项目,我可以在其中通过实例化它来测试我的 Controller ,将 dbContext 传递给构造函数。

 public class EventControllerTests
{
private readonly IEventRepository _eventRepository;
private readonly EventController _controller;
private readonly AppDbContext dbContext;

const string cn = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=EventDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

public EventControllerTests()
{

var options = new DbContextOptionsBuilder<EVNTS.Web.Database.AppDbContext>()
.UseSqlServer(cn).Options;
dbContext = new EVNTS.Web.Database.AppDbContext(options);
// Arrange
_eventRepository = new EventRepository(dbContext);
_controller = new EVNTS.Web.Controllers.EventController(_eventRepository);
}

[Fact]
public void ActionIndexTest()
{
// Act
var result = _controller.Index(1);

// Assert
var model = (Event)result.Model;
Assert.Equal(1, model.Id);
}
}

我有一个使用 WebApplicationFactory 的集成测试项目

 public class BasicTests : IClassFixture<WebApplicationFactory<EVNTS.Startup>>
{
private readonly WebApplicationFactory<EVNTS.Startup> _factory;
private readonly HttpClient _client;

public BasicTests(WebApplicationFactory<EVNTS.Startup> factory)
{
_factory = factory;
_client = _factory.CreateClient();
}

[Theory]
[InlineData("/")]
public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
{

// Act
var response = await _client.GetAsync(url);

// Assert
response.EnsureSuccessStatusCode(); // Status Code 200-299
Assert.Equal("text/html; charset=utf-8",
response.Content.Headers.ContentType.ToString());
}


[Fact]

public async Task TestUserRegistration()
{
var s = _factory.Services.GetRequiredService<EVNTS.Web.Repositories.IEventRepository>();
var url = "/user/register";
var inputModel = new EVNTS.Web.ViewModels.RegisterModel()
{
UserName = "eric",
Password = "123456",
ConfirmPassword = "123456"
};
var sObj = JsonSerializer.Serialize(inputModel);
var content = new StringContent(sObj, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await _client.PostAsync(url, content);
var result = response.Content.ReadAsStringAsync();
}

}

问题是,对于第二个选项,必须创建 View ,我需要使用像 AngleSharp 这样的库来测试结果。

我想要介于两者之间的东西,我可以直接调用构造函数并测试结果 View ,但 DI 会为我注入(inject) UserManager 和 dbContext。

有什么想法吗?

干杯

这是 Controller :

public class UserController : Controller
{
private readonly UserManager<User> _userManager;
public UserController(UserManager<User> userManager)
{
_userManager = userManager;
}

[HttpPost]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
IdentityResult? result=null;

if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.UserName);
if (user == null)
{
user = new User
{
Id = Guid.NewGuid(),
UserName = model.UserName,
};
result = await _userManager.CreateAsync(user, model.Password);
}
}
return View(result);
}
}

最佳答案

有时当您想在集成测试条件下检查 Controller 的结果而不检查 View 时,我也发现这很有用。

您可以使用依赖注入(inject)并从 WebApplicationFactory 创建范围。

        using (var serviceScope = Factory.Services.CreateScope())
{
var sut= serviceScope.ServiceProvider.GetService<YourController>();

}

要完成这项工作,您必须调用 Startup.cs 中的方法 AddControllersAsServices() 以在 DI 容器中注册 Controller

            services.AddControllersWithViews(options => { options.ConfigureMvcOptionsForPortalModule(); })
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddControllersAsServices();//add controller in DI to access it in integration testing

关于c# - 使用 asp.net core 进行集成测试(没有 View 的 Controller 测试),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564677/

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