2016-09-10 2 views
0

Итак, я был применен к модульному тесту, и я заметил, что разные модульные тесты не работают в nunit, а в Visual Studio с Resharper я попытался отладить его, и я получаю объектC# unit test терпит неудачу с moq, когда он идет, чтобы попасть в реальный сервис

[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 выглядит следующим образом FYI

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();

Ссылка на объект не установлен в случае ... ошибка Почему?

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; 
    } 
+0

Ну, предположительно, 'k.Type' имеет значение null, или' k' равно null. –

+0

thx, когда вы собираетесь поразить миллион очков ... я все еще жду hehe thx Jon –

+0

Вы уверены, что разместили правильный код для метода 'ProofKeyDocument'? Этот метод, который вы опубликовали, имеет другое имя и принимает разные параметры. –

ответ

0

Опубликовано тест не содержит макет метод "CreteJobTicket" и jobTickedId будет нулевым.

var jobTicketId = _uproduceRepo.CreateJobTicket(keyDocumentDetails.DocumentId, keyDocumentDetails.DataSourceId, "PROOF"); 
Смежные вопросы