【问题标题】:How do you mock a dependency using nSubstitute in abp framework,如何在 abp 框架中使用 nSubstitute 模拟依赖项,
【发布时间】:2020-09-04 01:36:50
【问题描述】:

在 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); 
        }
    }

授权类。 我需要使用 nSubstitute 将 IAutho 依赖替换为 Mocked 类

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  
        }

【问题讨论】:

    标签: c# testing nsubstitute abp


    【解决方案1】:

    github abp repo 的一位成员给了我正确的答案。您需要覆盖测试类上的 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);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多