C# 如何在NUnit中模拟操作?
嗨,我在NUnit测试用例中工作。例如,在业务层,我使用IOptionsC# 如何在NUnit中模拟操作?,c#,unit-testing,asp.net-core,nunit,moq,C#,Unit Testing,Asp.net Core,Nunit,Moq,嗨,我在NUnit测试用例中工作。例如,在业务层,我使用IOptions public MyBusinessLogic(IOptions<AuthenticationConfig> authenticationConfig, IOptions<ADFClient> AdfClient, IUnitOfWork unitOfWork) { _authenticationConfig = authenticationConfig.Value; _ADFClient = Adf
public MyBusinessLogic(IOptions<AuthenticationConfig> authenticationConfig, IOptions<ADFClient> AdfClient, IUnitOfWork unitOfWork)
{
_authenticationConfig = authenticationConfig.Value;
_ADFClient = AdfClient.Value;
UnitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
private AuthenticationConfig _authenticationConfig;
private ADFClient _ADFClient;
public MyBusinessLogic(IOptions authenticationConfig、IOptions AdfClient、IUnitOfWork unitOfWork)
{
_authenticationConfig=authenticationConfig.Value;
_ADFClient=ADFClient.Value;
UnitOfWork=UnitOfWork??抛出新的ArgumentNullException(nameof(UnitOfWork));
}
私有身份验证配置_AuthenticationConfig;
私人ADFClient(u ADFClient);;
下面是我的单元测试
[TestFixture]
public class MyBusinessLogicTests
{
[SetUp]
public void SetUp()
{
this.mockUnitOfWork = this.mockRepository.Create<IUnitOfWork>();
this.mockAuthenticationConfig = new Mock<IOptions<AuthenticationConfig>>();
this.mockADFClient = new Mock<IOptions<ADFClient>>();
}
private MockRepository mockRepository;
private Mock<IUnitOfWork> mockUnitOfWork;
private Mock<IOptions<AuthenticationConfig>> mockAuthenticationConfig;
private Mock<IOptions<ADFClient>> mockADFClient;
private ILogger<MyBusinessLogic> mockLogger;
private MytBusinessLogic CreateMyBusinessLogic()
{
return new MyBusinessLogic(
this.mockAuthenticationConfig,
this.mockADFClient,
this.mockUnitOfWork.Object
);
}
}
[TestFixture]
公共类MyBusinessLogicTests
{
[设置]
公共作废设置()
{
this.mockUnitOfWork=this.mockRepository.Create();
this.mockAuthenticationConfig=new Mock();
this.mockADFClient=new Mock();
}
私有MockRepository MockRepository;
私人模拟工作单元;
私有模拟mockAuthenticationConfig;
私有模拟mockADFClient;
私人ILogger模拟记录器;
私有MytBusinessLogic CreateMyBusinessLogic()
{
返回新的MyBusinessLogic(
this.mockAuthenticationConfig,
此.mockADFClient,
this.mockUnitOfWork.Object
);
}
}
在CreateMyBusinessLogic中,this.mockAuthenticationConfig给我一个错误,表示无法从Moq.Mock转换为Microosft.Extensions.Options.IOptions
有人能帮我修一下吗。任何帮助都将不胜感激。谢谢更改代码如下:
private MytBusinessLogic CreateMyBusinessLogic()
{
return new MyBusinessLogic(
this.mockAuthenticationConfig.Object,
this.mockADFClient.Object,
this.mockUnitOfWork.Object
);
}
使用
Moq
时,Mock
与IType
不同,您需要传递它的.Object
属性来访问模拟代理。如下更改代码:
private MytBusinessLogic CreateMyBusinessLogic()
{
return new MyBusinessLogic(
this.mockAuthenticationConfig.Object,
this.mockADFClient.Object,
this.mockUnitOfWork.Object
);
}
使用
Moq
时,Mock
与IType
不同,您需要传递它的.Object
属性来访问模拟代理。MockIOptions
通常比简单地创建实例没有多大价值。您可以使用jjst的Options.Create()
MockingIOptions
通常比创建实例没有多大价值。您可以使用jjstOptions.Create()