NSubtitute:模拟私有方法

时间:2019-08-23 02:42:17

标签: c# unit-testing nsubstitute

我正在使用NSubtitute,我想测试一个调用私有方法(在同一类中)的方法,因为私有方法调用SSRS来生成报告,实际上,它可以工作,但是我不想在单元测试中调用真实的报表服务器,因此我想对其进行模拟。

public static byte[] GenerateFinanceReport(long financeId, long userId, string currentLanguage, ReportDataVO reportDataVO, string reportName)
{
    var parameterValues = SetStandardParameters(userId, currentLanguage, reportDataVO);

    var paramFinanceId = new ParameterValue
    {
        Value = financeId.ToString(),
        Name = ParamFinanceId
    };
    parameterValues.Add(paramFinanceId );

    return GenerateReport(reportDataVO, parameterValues, reportName);
}


private static byte[] GenerateReport(ReportDataVO reportDataVO, List<ParameterValue> parameterValues, string reportName)
{
    var reportSerive = new ReportExecutionService.ReportExecutionService
    {
        Credentials = CredentialCache.DefaultNetworkCredentials,
        ExecutionHeaderValue = new ExecutionHeader()
    };
    reportSerive.LoadReport(reportName, null);
    ...
    return reportSerive.Render(...);
}

我想模拟调用返回GenerateReport(reportDataVO, parameterValues, reportName),并能够使用NSubtitute的Receive方法来检查每个测试用例向此调用输入的参数。

1 个答案:

答案 0 :(得分:3)

我们将必须重构代码,并通过例如 IGenerateReportService 的接口实现,将“ GenerateReport”方法移至新类,例如, GenerateReportService ,以便模拟该方法和按如下所示插入课程。

public class Class2bTested
{
    IGenerateReportService _IGenerateReportService;
    public (IGenerateReportService IIGenerateReportService)
    {
         _IIGenerateReportService=IIGenerateReportService;
    }

    public byte[] GenerateFinanceReport(long financeId, long userId, string currentLanguage, ReportDataVO reportDataVO, string reportName)
    {
        var parameterValues = SetStandardParameters(userId, currentLanguage, reportDataVO);

        var paramFinanceId = new ParameterValue
        {
            Value = financeId.ToString(),
            Name = ParamFinanceId
        };
        parameterValues.Add(paramFinanceId );

        return _IGenerateReportService.GenerateReport(reportDataVO, parameterValues, reportName);
     }
 }

新类如下:

  public interface IGenerateReportService
  {
      GenerateReport(ReportDataVO reportDataVO, List<ParameterValue> parameterValues, string reportName);
  }    
  public class GenerateReportService:IGenerateReportService
  {
       public byte[] GenerateReport(ReportDataVO reportDataVO, List<ParameterValue> parameterValues, string reportName)
        {
         var reportSerive = new ReportExecutionService.ReportExecutionService
         {
               Credentials = CredentialCache.DefaultNetworkCredentials,
                ExecutionHeaderValue = new ExecutionHeader()
         };
         reportSerive.LoadReport(reportName, null);

          return reportSerive.Render();
}

现在有了此代码,我们可以模拟 IGenerateReportService 的方法 GenerateReport