AssertJ抛出测试失败

AssertJ抛出测试失败

问题描述:

我想在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

assertThatThrownBy if if if给定的拉姆达不会抛出异常,在你的情况下,() -> batchManager.insertBatchParts(batchPartViewNext, userName)应该抛出ValidationError,但它显然没有。