1

私はMOQを初めて使用し、現在学習中です。単体テストを作成する必要があるタスクを取得しましたが、見つけることができなかった以下のエラーが発生しています。誰でもこれで私を助けてください。また、コードを確認して、テストケースに変更が必要な場合はアドバイスをください。

想定: IAcronisService.GetActivitiesFromDate("mygroup", 2016 年 5 月 24 日 8:33:34 PM) の呼び出しは、模擬動作 Strict で失敗しました.....

Saveメソッドの場合(例外がスローされたsaveメソッドでコメントしました)

Process メソッド呼び出し save メソッド

public int Process()
{
    AcronisService = AcronisSvcManager.Get(ClientFactory, DataProviderFactory, LogAdapter);

    DataObject backupGroupsDO = GetListOfAllCurrentGroups();

    int activitiesSavedCount = Save(backupGroupsDO);
    return activitiesSavedCount;
}

デバッグ時に、上記のプロセス メソッドの最初の行にマウスを合わせると、以下の行も表示されます。サービスオブジェクトは呼び出し/モックではないと思いました。これは上記の例外と関係がありますか? いくつかの変更を提案してください。

(IAcronisServiceProxy)AcronisService).AcronisURLタイプ MOQ.MockException の例外をスローしました。

Save メソッド

private int Save(DataObject backupGroupsDO)
{
    int count = 0;

    foreach (DataRecord dr in backupGroupsDO.DataRecord)
    {
        BackupGroup backupGroup = new BackupGroup(dr);

        // Get all activities for each group
        AcronisClient.DataModel.Activity.ActivitiesResponse acronisActivities;
        if (backupGroup.LastActivityDate == null)
        {
            // Get all activities for each group
            ***//Got Exception at this line***
            acronisActivities = AcronisService.GetActivitiesFromDate(backupGroup.GroupName, DateTime.Now.AddDays(-90)); 
        }
        else
        {
            acronisActivities = AcronisService.GetActivitiesFromDate(backupGroup.GroupName, backupGroup.LastActivityDate);
        }



        if (acronisActivities == null || acronisActivities.Activities == null)
        {
            // Stop processing b/c might be an issue with the connection to Acronis
            LogAdapter.LogError(KCBLog.Main, "Stopped processing activities, possible Acronis connection issue with getting Activities");
            return -1;
        }
        var lastBackUpActivity = acronisActivities.Activities.OrderByDescending(z => z.StartTime).FirstOrDefault();

        List<string> lastSuccessfulActivities = new List<string>();
        List<string> lastActivities = new List<string>();

        foreach (var acronisActivity in acronisActivities.Activities)
        {

            Kaseya.KCB.Common.DataModels.AcronisActivity activity = new AcronisActivity();
            activity.BackupPlanId = acronisActivity.BackupPlanId;
            activity.BytesProcessed = acronisActivity.BytesProcessed;
            activity.BytesSaved = acronisActivity.BytesSaved;


            activity.Cause = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Cause;
            activity.Reason = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Reason;
            activity.Effect = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Effect;

            activity.DateCreated = DateTime.Now;

            activity.FinishTime = acronisActivity.FinishTime;
            activity.GroupId = backupGroup.Id;
            activity.Id = acronisActivity.Id;
            activity.InitiatedBy = acronisActivity.InitiatedBy;
            activity.InstanceId = acronisActivity.InstanceId;
            activity.IsRootActivity = (bool)acronisActivity.IsRootActivity;
            activity.ParentActivityId = acronisActivity.ParentActivityId;
            activity.PartitionId = PartitionId;
            activity.StartTime = acronisActivity.StartTime;
            activity.State = acronisActivity.State;
            activity.Status = acronisActivity.Status;
            activity.Title = acronisActivity.Title;
            activity.UpdateTime = acronisActivity.UpdateTime;

            AcronisActivityDataProvider.AddUpdateAcronisActivity(activity);

            AcronisClient.DataModel.Activity.Activity lastSuccessfulActivity = acronisActivities.Activities.Where(z => z.Status == "ok" && z.Title.Contains("Running backup plan") && z.InstanceId==acronisActivity.InstanceId).OrderByDescending(z => z.FinishTime).FirstOrDefault();
            var lastActivity = acronisActivities.Activities.Where(z => z.Title.Contains("Running backup plan") && z.InstanceId == acronisActivity.InstanceId).OrderByDescending(z => z.FinishTime).FirstOrDefault();


            if (!string.IsNullOrEmpty(acronisActivity.InstanceId))
            {
                DataRecord assetDR = AssetDataProvider.GetByInstanceId(acronisActivity.InstanceId, PartitionId);
                if (assetDR != null)
                {
                    var assetId = assetDR.FindValue<string>("id", "");

                    if (lastSuccessfulActivity != null && !lastSuccessfulActivities.Contains(acronisActivity.InstanceId))
                    {
                        AssetDataProvider.UpdateLastSuccessfulActivityId(assetId, lastSuccessfulActivity.ParentActivityId);
                        lastSuccessfulActivities.Add(acronisActivity.InstanceId);
                    }
                    if (lastActivity != null && !lastActivities.Contains(acronisActivity.InstanceId))
                    {
                        AssetDataProvider.UpdateLastActivityId(assetId, lastActivity.ParentActivityId);
                        lastActivities.Add(acronisActivity.InstanceId);
                    }
                }
            }
            count++;
        }

        if (acronisActivities.Activities != null && acronisActivities.Activities.Count>0)
        {
            //backupGroup.LastActivityDate = lastBackUpActivity.StartTime;
            BackupGroupDataProvider.UpdateLastBackupGroupActivityDate(backupGroup.Id, lastBackUpActivity.StartTime);
        }
    }

    return count;
}

私が書いたテスト方法、

public void Test()
{
    string groupName = "mygroup";
    string mybackupAccountName = "mybackupaccount";
    decimal PartitionId = 9m;
    DateTime lastActivityDate = DateTime.Parse("2016-08-14T20:47:05");
    string instanceId = "utinstanceId";
    string assetId = "123";


    DataRecord asset = new DataRecord();
    asset.AddField("id", 123);

    DataObject backupGroupsDO = new DataObject();
    DataRecord groupDataRecord = new DataRecord();
    groupDataRecord.AddField("id", 123);
    groupDataRecord.AddField("partitionId", PartitionId);
    groupDataRecord.AddField("groupName", groupName);

    //groupDataRecord.AddField("lastActivityDate", lastActivityDate);

    groupDataRecord.AddField("backupAccountName", mybackupAccountName);
    backupGroupsDO.DataRecord.Add(groupDataRecord);

    AcronisActivity acronisActivity = new AcronisActivity();
    acronisActivity.BackupPlanId = "utBackupPlanId";

    ActivitiesResponse activitiesResponse = new ActivitiesResponse();
    AcronisClient.DataModel.Activity.Activity activity = new AcronisClient.DataModel.Activity.Activity();
    activity.BackupPlanId = "utackupPlanId";
    activity.BytesProcessed = 124674;
    activity.BytesSaved = 06446;
    activity.CompletionResult = new CompletionResult()
    {
        Cause = "utCause",
        Reason = "utReason",
        Effect = "utEffect"
    };
    activity.FinishTime = DateTime.Parse("2016-08-14T20:47:04");
    activity.Id = "utId";
    activity.InitiatedBy = "utInitiatedBy";
    activity.InstanceId = "utInstanceId";
    activity.IsRootActivity = true;
    activity.ParentActivityId = "utParentActivityId";
    activity.StartTime = DateTime.Parse("2016-08-14T20:47:02");
    activity.State = "utState";
    activity.Status = "utStatus";
    activity.Title = "utTitle";
    activity.UpdateTime = DateTime.Parse("2016-08-14T20:47:03");

    activitiesResponse.Activities = new List<AcronisClient.DataModel.Activity.Activity>();
    activitiesResponse.Activities.Add(activity);

    var moqFactory = new MockRepository(MockBehavior.Strict);

    var moqDataProviderFactory = moqFactory.Create<IDataProviderFactory>();
    var moqDataProvider = moqFactory.Create<IDataProvider>();
    var moqLogAdapter = moqFactory.Create<ILogAdapter>();
    var moqAcronisServiceManager = moqFactory.Create<IAcronisServiceManager>();
    var moqAcronisService = moqFactory.Create<IAcronisService>();
    var moqAssetDataProvider = moqFactory.Create<IAssetDataProvider>();
    var moqAcronisActivityDataProvider = moqFactory.Create<IAcronisActivityDataProvider>();
    var moqBackupGroupDataProvider = moqFactory.Create<IBackupGroupDataProvider>();


    Credential MSPCredential = new Credential();

    moqDataProviderFactory.Setup(m => m.BackupGroupDataProvider.GetBackupGroups()).Returns(backupGroupsDO);

    moqAcronisServiceManager.Setup(m => m.Get(It.IsAny<IRestClientFactory>(), It.IsAny<IDataProviderFactory>(), It.IsAny<ILogAdapter>(), "")).Returns(moqAcronisService.Object);

    moqDataProvider.Setup(m => m.VerifyPartitionId(ref PartitionId));
    moqDataProvider.Setup(m => m.ExecuteNonQuery(It.IsAny<AddUpdateAcronisActivity>())).Returns(1);
    moqAcronisService.Setup(m => m.GetActivitiesFromDate(groupName, lastActivityDate)).Returns(activitiesResponse);
    moqAcronisActivityDataProvider.Setup(m => m.AddUpdateAcronisActivity(acronisActivity));
    moqAssetDataProvider.Setup(m => m.GetByInstanceId(instanceId, PartitionId,1)).Returns(asset);
    moqAssetDataProvider.Setup(m => m.UpdateLastActivityId(assetId, activity.ParentActivityId));
    moqAssetDataProvider.Setup(m => m.UpdateLastSuccessfulActivityId(assetId, activity.ParentActivityId));
    moqBackupGroupDataProvider.Setup(m => m.UpdateLastBackupGroupActivityDate("1234", lastActivityDate));

    // moqAcronisService.Setup(m => m.GetActivitiesFromDate(groupName, Convert.ToDateTime("2016-08-18T13:18:40.000Z"))).Returns(activitiesResponse);


    ActivityHarvester activityHarvester = new ActivityHarvester();

    activityHarvester.PartitionId = PartitionId;
    activityHarvester.DataProvider = moqDataProvider.Object;
    activityHarvester.LogAdapter = moqLogAdapter.Object;
    activityHarvester.AcronisSvcManager = moqAcronisServiceManager.Object;
    activityHarvester.DataProviderFactory = moqDataProviderFactory.Object;
    activityHarvester.AcronisService = moqAcronisService.Object;
    activityHarvester.AssetDataProvider = moqAssetDataProvider.Object;
    activityHarvester.BackupGroupDataProvider = moqBackupGroupDataProvider.Object;
    activityHarvester.AcronisActivityDataProvider = moqAcronisActivityDataProvider.Object;


    activityHarvester.process();//*process method calls above save method method* 
    moqFactory.VerifyAll();
}
4

1 に答える 1

1

あなたの例から、セットアップはコードに基づいてIAcronisService.GetActivitiesFromDate期待していることを示していますが、エラーは、予想とは異なる日付を使用したことを示しています。moq の動作がであるため、これはlastActivityDate2016-08-14T20:47:055/24/2016 8:33:34 PMStrict

モックが、対応するセットアップを持たない呼び出しに対して常に例外をスローするようにします。

を使用して、セットアップをもう少し柔軟にすることができますIt.IsAny<DateTime>()

moqAcronisService
    .Setup(m => m.GetActivitiesFromDate(groupName, It.IsAny<DateTime>()))
    .Returns(activitiesResponse);

Defaultまたは、使用する moq ファクトリまたはMockBehaviorの動作を変更しますLoose

于 2016-08-23T10:19:25.410 に答える