问题描述
在Abp框架中,我试图为FamilyAppService类编写一个测试(请参见下文)。我需要在FamilyAppService的构造函数中模拟IAutho实例。我尝试模拟IAutho,然后将其添加到FamilyAppService的新实例中(而不是使用GetrequiredService()),但是ObjectMapper出现“ System.ArgumentNullException”错误。
FamilyAppService类
public class FamilyAppService : KmAppService,IFamilyAppService {
private readonly IAutho autho;
public FamilyAppService(
IAutho autho) {
this.autho = autho;
}
public virtual async Task SendRequest(SendRequestInput input) {
var family = ObjectMapper.Map<FamilyDto,Family>(input.Family);
// code ...
await autho.FindUserIdByEmail(family.Email);
}
}
Autho类。 我需要使用nSubstitute将IAutho依赖项替换为模拟类
public class Autho : IAutho,ITransientDependency {
public Autho( ) {
}
public virtual async Task<User> FindUserIdByEmail(string input) {
// Don’t want this code touched in test
// Code ...
}
}
我当前的测试...
[Fact]
public async Task ShouldSendEmail() {
var autho = Substitute.For<IAutho>();
autho.FindUserIdByEmail(Arg.Any<string>()).Returns((User)null);
var familyAppService = new FamilyAppService(autho);
// var familyAppService = GetrequiredService<IFamilyAppService>();
// setup input code here..
// get ObjectMapper error here
await familyAppService.SendRequest(input);
// Assert
}
解决方法
github abp仓库中的一位成员给了我正确答案。您需要在测试类上重写AfterAddApplication方法,并将替代/模拟添加到services.AddSingletone。
示例...
protected override void AfterAddApplication(IServiceCollection services) {
var autho = Substitute.For<IAutho>();
autho.FindUserIdByEmail(Arg.Any<string>()).Returns((User)null);
services.AddSingleton(autho);
}