services.AddDbContext
using Microsoft.EntityFrameworkCore; using MySql.Data.EntityFrameworkCore.Extensions;
public class MyTestFixture { public MyDbContext Context { get; private set; }
public MyTestFixture()
{
var options = new DbContextOptionsBuilder()
.UseMySQL("server=localhost; database=my_database; uid=root; password=my_password;")
.Options;
Context = new MyDbContext(options);
Context.Database.EnsureCreated();
// Add test data here...
}
}
using Microsoft.AspNetCore.Mvc; using Xunit;
public class MyControllerTests : IClassFixture
public MyControllerTests(MyTestFixture fixture)
{
_context = fixture.Context;
}
[Fact]
public void MyAction_Returns_OkResult()
{
var controller = new MyController(_context);
var result = controller.MyAction();
Assert.IsType(result);
}
}
注意:在添加MySQL服务和测试数据源时,请确保正确配置MySQL连接字符串。