2017-02-03 119 views
0

我想在junit中使用AsssertJ做一個異常測試用例。但是我收到以下錯誤: 結果:AssertJ拋出測試失敗

失敗測試: BatchManagerTests.testUniqueBatchpart:225期望代碼提高可拋出。

測試運行:149,故障:1,錯誤:0,跳過:0


的測試用例的代碼是

@Test 
    public void testUniqueBatchpart(){ 
     String userName = "502689031"; 
     List<BatchPartView> batchPartViewList = new ArrayList(); 
     BatchPart batchPart = initBatchPart(new BatchPart(), 1L, 1L, 1L, 1L, false); 
     BatchPart batchPartNext = initBatchPart(new BatchPart(), 2L, 1L, 1L, 2L, false); 
     BatchPartView batchPartView = initBatchPartView(batchPart);  
     BatchPartView batchPartViewNext = initBatchPartView(batchPartNext); 

     batchPartView = batchManager.insertBatchParts(batchPartView, userName); 
     batchManager.insertBatchParts(batchPartViewNext, userName); 

     assertThatThrownBy(() -> batchManager.insertBatchParts(batchPartViewNext, userName)) 
          .isInstanceOf(ValidationError.class) 
          .hasMessage(" Unique constraint violation encountered"); 


    } 

我想測試的代碼:

public BatchPartView insertBatchParts(BatchPartView batchPartView, String userName) { 
     if (LOGGER.isDebugEnabled()) { 
      LOGGER.debug("BatchManager:::insertBatchParts()"); 
     } 
     Batch batch; 
     BatchPartView returnBatchPartView = null; 
     try { 
      batch = batchRepository.findByMachineIdAndActiveTrue(batchPartView.getPart().getMachineId()); 
      Long falseCount = batchPartsRepository 
        .countByBatchIdInAndPartIdInAndDeletedFalse(batchPartView.getBatchId(), 
          batchPartView.getPart().getId()); 

      if (null == batch) { 
       batch = batchPartEngine.saveBatch(batchPartView, userName); 
       returnBatchPartView = batchPartEngine.saveBatchPart(batchPartView, batch, userName); 
      } else { 
       if (falseCount < 1) { 
        returnBatchPartView = batchPartEngine.saveBatchPart(batchPartView, batch, userName); 
       } 
       else { 
        Set<BRSValidationError> errorSet = new HashSet<>(); 
        errorSet.add(new BRSValidationError(ERROR, UNIQUECONSTRAINTVIOLATION)); 
        if (!errorSet.isEmpty()) { 
         throw new ValidationError(errorSet); 
        } 
       } 
      } 
     } catch (Exception ex) { 
      LOGGER.error("", ex); 
      Set<BRSValidationError> errorSet = new HashSet<>(); 
      errorSet.add(new BRSValidationError(ERROR, ex.getMessage())); 
      if (!errorSet.isEmpty()) { 
       throw new ValidationError(errorSet); 
      } 
     } 
     return returnBatchPartView; 
    } 
+0

請附上日誌以便於理解 – rajadilipkolli

回答

0

assertThatThrownBy if if if給定的拉姆達不會拋出異常,在你的情況下,() -> batchManager.insertBatchParts(batchPartViewNext, userName)應該拋出ValidationError,但它顯然沒有。