【发布时间】:2022-01-28 18:06:12
【问题描述】:
我是单元测试和 DI 的新手,我找不到在使用依赖注入设计的类中调用方法的简单方法。
这是我的课
public class AgentProvisioningServiceHelpher : IAgentProvisioningServiceHelpher
{
private readonly IExcelParser _excelParser;
private readonly SupervisorDbContext _SupervisorDbContext;
private readonly SchedulerNoTrackingDbContext _SchedulerDbContext;
// constructor
public AgentProvisioningServiceHelpher(IExcelParser excelParser, SupervisorDbContext supervisorDbContext, SchedulerNoTrackingDbContext SchedulerDbContext)
{
_excelParser = excelParser;
_SupervisorDbContext = supervisorDbContext;
_SchedulerDbContext = SchedulerDbContext;
}
// Function that I want to call in unit test
public int SimpleMethodToTest(int InputId)
{
return InputId + 1;
}
}
这是我的界面代码
public interface IAgentProvisioningServiceHelpher
{
int SimpleMethodToTest(int InputId);
}
这是我的单元测试代码,我正在使用 Xunit
public class UnitTest1
{
private IAgentProvisioningServiceHelpher _sut;
private IExcelParser _excelParser;
private SupervisorDbContext _DBcontext1;
private SchedulerNoTrackingDbContext _DBcontext2;
public UnitTest1(IExcelParser excelParser, SupervisorDbContext DBcontext1, SchedulerNoTrackingDbContext DBcontext2, IAgentProvisioningServiceHelpher sut)
{
_excelParser = excelParser;
_DBcontext1 = DBcontext1;
_DBcontext2 = DBcontext2;
_sut = sut;
}
[Fact]
public void SimpleMethodToTest_Shall_ReturnPlus1()
{
// Arrange
int Input_Int = 1;
// Act
// I try to tell the interface to map with the class I want to test
IAgentProvisioningServiceHelpher _sut = new AgentProvisioningServiceHelpher(_excelParser, _DBcontext1, _DBcontext2);
// Then I try to call the interface method
var result = _sut.SimpleMethodToTest(Input_Int);
// Assert
Assert.Equal(2, result);
}
}
当我尝试运行测试时,Visual Studio 报错 - 我该如何解决这个问题?
UnitTest1.cs 第 33 行
以下构造函数参数没有匹配的夹具数据:IExcelParser excelParser、SupervisorDbContext DBcontext1、SchedulerNoTrackingDbContext DBcontext2、IAgentProvisioningServiceHelpher sut
【问题讨论】:
-
Xunit 没有使用 DI 来解析引用,所以删除构造函数参数并尝试创建一个模拟。
-
在 V3 中有一个关于这类事情的开放功能请求,但它没有完成并且在 V2 中没有定义,它仅适用于 xunit.net/docs/shared-context
标签: c# unit-testing dependency-injection xunit.net