1

我有一个单元测试来测试是否正确引发了自定义异常。但我得到了一个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 的结果是否失败。你能帮忙吗

4

2 回答 2

1

create引发InvalidLength异常,然后捕获它并静默处理它,您的测试期望它实际引发它。

使用与 不同的断言assertRaises。该except块返回一个 json,因此您的测试可以检查 json 的内容。

于 2017-08-15T10:51:40.537 回答
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在代码中捕获异常。

我认为考虑到您的用例,您应该更新测试以检查响应消息是否正确。

于 2017-08-15T10:53:59.457 回答