2017-08-15 15 views
-1

我有一個unittest測試自定義異常是否正確引發。但我得到Asse田:InvalidLength沒有提出AssertionError:異常未提出

下面是我的單元測試

@patch('services.class_entity.validate') 
@patch('services.class_entity.jsonify') 
def test_should_raise_invalid_length_exception(self, mock_jsonify, mock_validate): 
    mock_validate.return_value = True 

    data = self.data 
    data['traditional_desc'] = "Contrary to popular" 
    mock_jsonify.return_value = { 
     "success": False, 
     "results": { 
      "message": "Invalid value for traditional_desc" 
     } 
    } 

    with self.assertRaises(InvalidLength) as cm: 
     BenefitTemplateService.create(data) 

這是我測試

class BenefitTemplateService(object): 

    @staticmethod 
    def create(params): 

     try: 
      required_fields = ['company_id', 'name', 'behavior', 'benefit_type'] 
      valid = is_subset(params, required_fields) 

      if not valid: 
       raise MissingParameter 

      if not validate_string(params['traditional_desc'], 0, 1000, characters_supported="ascii"): 
       raise InvalidLength(400, "Invalid value for traditional_desc") 

      # Call create here 
      response = BenefitTemplateEntityManager.create_template(params) 
      return response 

     except InvalidLength as e: 
      response = { 
       "success": False, 
       "results": { 
        "message": e.message 
       } 
      } 

      return jsonify(response), e.code 

除了InvalidLength是函數正常工作,因爲如果我嘗試打印它執行該代碼行。所以我認爲InvalidLength異常被調用,但我不知道我的unittest結果失敗。你能幫忙嗎

回答

1

create引發InvalidLength異常,但後來捕獲它並靜默處理它,在那裏你的測試期望它實際提高它。

使用與assertRaises不同的斷言。 except塊返回一個json,所以你的測試可以檢查json的內容。

+0

我該如何解決這個問題?我需要我的測試來告訴我,真的發生了異常。如果我刪除除了代碼之外的代碼,我可以解決這個問題,但是我會失去靈活性我的回覆 –

+0

@MadzmarUllang然後使用與assertRaises不同的斷言。你返回一個json,所以你的測試可以檢查json的內容。 – DeepSpace

0

你提出的例外正常

if not validate_string(params['traditional_desc'], 0, 1000, characters_supported="ascii"): 
    raise InvalidLength(400, "Invalid value for traditional_desc") 

然後你抓住它,並返回一個JSON

except InvalidLength as e: 
    response = { 
     "success": False, 
     "results": { 
      "message": e.message 
     } 
    } 

    return jsonify(response), e.code 

因此異常不傳播到測試。

2種方法來解決這個問題:

  • 在您的測試,檢查JSON響應是正確的。 「traditional_desc的值無效」
  • 或不要在代碼中捕獲InvalidLength異常。

我認爲考慮你的用例,你應該更新你的測試來檢查響應消息是否正確。

+0

我認爲第一個選項更適合我的情況,因爲我不想刪除我的catch代碼。 –

+0

是的。這也是我的感受。 :) –