4 c# xunit .net-core asp.net-core
集成测试中如何进行依赖注入?调用departmentRepository或departmentAppService,会给我带来null下面的错误。
public class DepartmentAppServiceTest
{
public SharedServicesContext context;
public IMapper mapper;
public IRepository<Department, int> departmentRepository;
public IDepartmentAppService departmentAppService;
public DepartmentAppServiceTest()
{
ServiceCollection services = new ServiceCollection();
services.AddTransient<IRepository<Department>, BaseRepository<Department>>();
services.AddTransient<IDepartmentAppService, DepartmentAppService>();
Run Code Online (Sandbox Code Playgroud)
调试和设置断点,调用此存储库或应用程序服务均为空,
新方法
[Fact]
var departmentDto = await departmentAppService.GetDepartmentById(2);
Run Code Online (Sandbox Code Playgroud)
应用服务的构造函数
DepartmentAppService(departmentRepository, mapper)
DepartmentRepository(dbcontext)
Run Code Online (Sandbox Code Playgroud)
错误:
消息:System.NullReferenceException:未将对象引用设置为对象的实例。
对于我们的集成测试,我们以编程方式启动应用程序并使用 HttpClient 对 API 端点进行调用。这样您的应用程序就会运行整个启动过程,并且依赖项注入就像一个魅力。
这是服务器启动和客户端创建的示例,它可以重复用于多个测试:
_server = new TestServer(new WebHostBuilder()
.UseEnvironment("Testing")
.UseContentRoot(applicationPath)
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(applicationPath)
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Testing.json")
.Build()
)
.UseStartup<TestStartup>());
_client = _server.CreateClient();
// Act
var response = await _client.GetAsync("/");
// Assert
response.EnsureSuccessStatusCode();
Run Code Online (Sandbox Code Playgroud)
微软也通过 HttpClient 对此进行了记录:
https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests ?view=aspnetcore-2.2
| 归档时间: |
|
| 查看次数: |
13790 次 |
| 最近记录: |