c#单元测试在moq碰到真正的服务时会失败

本文关键字:服务 失败 单元测试 moq | 更新日期: 2023-09-27 18:06:37

所以我被放在做单元测试,我注意到不同的单元测试失败在nunit和Visual Studio与Resharper我试着调试它,我得到对象

   [Test]
    public void KeyDocumentService_ProofKeyDocument_RepoReturnsData_ServiceReturnsTheDataWithoutError()
    {
        //Arrange
        KeyDocumentProofRequest request = new KeyDocumentProofRequest() { KeyDocumentId = 2 };
        string returnedResponse = "2";
        KeyDocument keyDocumentResponse = new KeyDocument() { CampaignId = "2", DesignFileId = 3,DocumentId="2", DataSourceId="3", KeyDocumentId=1 };
        List<vwKeyDocumentSearch> keyListResponse = new List<vwKeyDocumentSearch>() { new vwKeyDocumentSearch { FieldName = "test", FieldValue = "testvalue" } };
        var uproduceRepo = new Mock<IUProduceRepository>();
        var keyDocRepo = new Mock<IKeyDocumentRepository>();
        var templateRepo = new Mock<ITemplateRepository>();
        keyDocRepo.Setup(p => p.GetKeyDocument(It.IsAny<KeyDocumentRequest>())).Returns(new KeyDocumentResponse() { data = keyDocumentResponse });
        keyDocRepo.Setup(p => p.GetKeyDocumentItems(It.IsAny<int>())).Returns(keyListResponse);
        uproduceRepo.Setup(p => p.ProduceDocument(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customization[]>(), It.IsAny<string>(), It.IsAny<string>(), null)).Returns(returnedResponse);
        // Act.
        KeyDocumentService svc = new KeyDocumentService(keyDocRepo.Object, uproduceRepo.Object, templateRepo.Object);
        var response = svc.ProofKeyDocument(request);
        //Assert
        Assert.IsNotNull(response);
        Assert.IsNotNull(response.data.JobId);
        Assert.IsNull(response.Error);
    }

所以错误发生在这一行:

var response = svc.ProofKeyDocument(request);

单元测试应该进入真正的服务吗?或者这样可以吗?

方法ProofKeyDocument看起来像这样供参考

    private List<Customization> GetCustomizationsFromKeyDocumentItems(List<vwKeyDocumentSearch> keyDocumentItemsList,
                                        int templateId, int clientId)
    {
        try
        {
            List<Customization> KeyDocumentCustomizations = new List<Customization>();
            var keyDocumentVariableList = keyDocumentItemsList.Where(k => k.Type.ToUpper()=="VARIABLE").ToList();
            var keyDocumentSettingList = keyDocumentItemsList.Where(k => k.Type.ToUpper() == "SETTING").ToList();
            var keyDocumentContentList = keyDocumentItemsList.Where(k => k.Type.ToUpper() == "CONTENT").ToList();
            KeyDocumentCustomizations.AddRange(VariableCustomizations(keyDocumentVariableList, templateId));
            KeyDocumentCustomizations.AddRange(SettingCustomizations(keyDocumentSettingList, templateId));
            KeyDocumentCustomizations.AddRange(ContentCustomizations(keyDocumentContentList, templateId, clientId));
            return KeyDocumentCustomizations;
        }
        catch (Exception ex)
        {
            logger.Error(string.Format("Error customizing key document: {0}", templateId), ex);
            throw ex;
        }
    }

我看到在这行调试时,它会爆炸var keyDocumentVariableList = keyDocumentItemsList.Where(k => k.Type.ToUpper()=="VARIABLE").ToList();

对象引用未设置为instance…为什么?

 var keyDocumentResponse = _repo.GetKeyDocument(new KeyDocumentRequest() { KeyDocumentId = request.KeyDocumentId });

  Customization[] customizations = GenerateCustomizationsForKeyDocument(keyDocumentDetails.KeyDocumentId, keyDocumentResponse);
然后

    public KeyDocumentProofResponse ProofKeyDocument(KeyDocumentProofRequest request)
    {
        //return new KeyDocumentProofResponse()
        //{
        //    data = new KeyDocumentProofResponseData() { JobId = "2984" }
        //};
        KeyDocumentProofResponse response = new KeyDocumentProofResponse();
        var keyDocumentDetails = _repo.GetKeyDocument(new KeyDocumentRequest() { KeyDocumentId = request.KeyDocumentId }).data;
        if (keyDocumentDetails != null && (!string.IsNullOrEmpty(keyDocumentDetails.CampaignId)) &&
                keyDocumentDetails.DesignFileId.HasValue &&
                keyDocumentDetails.DesignFileId > 0)
        {
            var keyDocumentResponse = _repo.GetKeyDocument(new KeyDocumentRequest() { KeyDocumentId = request.KeyDocumentId });
            Customization[] customizations = GenerateCustomizationsForKeyDocument(keyDocumentDetails.KeyDocumentId, keyDocumentResponse);
            var jobTicketId = _uproduceRepo.CreateJobTicket(keyDocumentDetails.DocumentId, keyDocumentDetails.DataSourceId, "PROOF");
            if (!string.IsNullOrEmpty(jobTicketId))
            {
                List<JobDataSource> dataSources = GenerateCSVForPersonalizedAndCustomizedVariables(keyDocumentResponse, jobTicketId);
                var jobId = _uproduceRepo.ProduceDocument(keyDocumentDetails.DocumentId, keyDocumentDetails.DataSourceId, customizations, "PROOF", jobTicketId, dataSources);
                if (string.IsNullOrEmpty(jobId))
                {
                    response.Error = CreateCustomError("Error while submitting job", "Error occurred while submitting proofing job");
                }
                else
                {
                    response.data.JobId = jobId;
                }
            }
            else
            {
                response.Error = CreateCustomError("Unable to generate job ticket for the keydocument",
                "Error while creating a job ticket for proof request");
            }
        }
        else
        {
            response.Error = CreateCustomError("Unable to generate proof for the keydocument",
                "Requested template is missing campaignid or Designfile in Uproduce");
        }
        return response;
    }

c#单元测试在moq碰到真正的服务时会失败

已发布的测试不包含"CreteJobTicket"的模拟方法,并且jobTickedId将为null。

var jobTicketId = _uproduceRepo.CreateJobTicket(keyDocumentDetails.DocumentId, keyDocumentDetails.DataSourceId, "PROOF");