我有一个单元测试来测试是否正确引发了自定义异常。但我得到了一个AssertionError: InvalidLength not raise
下面是我的单元测试
@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
except InvalidLength工作正常,因为如果我尝试打印它会执行那行代码。所以我假设 InvalidLength Exception 正在被调用,但我不确定我的 unittest 的结果是否失败。你能帮忙吗