如何在abp框架中使用Subsubstitute来模拟依赖关系



在Abp框架中,我正试图为我的FamilyAppService类编写一个测试(见下文(。我需要在FamilyAppService的构造函数中模拟一个IAutho实例。我试着嘲笑IAutho,然后将其添加到FamilyAppService的新实例中(而不是使用GetRequiredService(((,但我在ObjectMapper中遇到了"System.ArgumentNullException"错误。

家庭应用服务类

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类。我需要用一个使用取代的模拟类来代替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 repo的一位成员给了我正确的答案。您需要重写测试类上的AfterAddApplication方法,并将substitue/mmock添加到服务中。AddSingletone。

示例。。。

protected override void AfterAddApplication(IServiceCollection services) {

var autho = Substitute.For<IAutho>();
autho.FindUserIdByEmail(Arg.Any<string>()).Returns((User)null);
services.AddSingleton(autho);
}

最新更新