如何在 python 中创建一个在引发异常时通过的测试用例?

How to create a test case in python which passes if an exception is raised?

我的代码测试输入的电子邮件和用户名是否相同,如果不同则引发错误。我正在尝试测试代码,如果引发异常,它应该通过,但我得到了异常,但测试仍然失败。 代码:

def is_valid_email(email, cognitoUsername):
    if email != cognitoUsername:
        print("User email invalid")
        raise Exception("Username and Email address must be the same")
    print("User email valid")
    return True

测试:

self.assertEqual(lambda_function.is_valid_email("test@email.com", "test@email.com"), True)
self.assertRaises(Exception, lambda_function.is_valid_email("test@email.com", "test"))

错误:


email = 'test@email.com', cognitoUsername = 'test'

    def is_valid_email(email, cognitoUsername):
        if email != cognitoUsername:
            print("User email invalid")
>           raise Exception("Username and Email address must be the same")
E           Exception: Username and Email address must be the same

../lambda_function.py:32: Exception




============================== 1 failed in 0.53s ===============================

Process finished with exit code 1

你的测试代码应该调用 assertRaises() 和一个可调用对象:

self.assertRaises(Exception, lambda: lambda_function.is_valid_email("test@email.com", "test"))

另一种选择是像这样使用 with

with self.assertRaises(Exception):
    lambda_function.is_valid_email("test@email.com", "test")