简体   繁体   English

测试异常失败

[英]Testing for exception fails

When I save a User model, I would like to check if it has a username. 保存用户模型时,我想检查它是否具有用户名。 Therefore I wrote this pre_save : 因此,我写了这个pre_save

@receiver(pre_save, sender=User)
def validate_user(sender, instance, **kwargs):
    if len(instance.username) <= 5: raise Exception("Username too short")

Now in my testing method I would like to test this exception: 现在,在我的测试方法中,我想测试此异常:

def test_user_no_username(self):
    u = User.objects.create()
    self.assertRaises(Exception, u.save())

The test fails. 测试失败。 Why? 为什么?

assertRaises is kind of a specific exception - as a second argument you should pass a callable : assertRaises是一种特定的异常- 作为第二个参数,您应该传递一个callable

assertRaises(exception, callable, *args, **kwds)

In other words, don't call u.save() : 换句话说,不要调用u.save()

self.assertRaises(Exception, u.save)

Also, you should really think about having custom exceptions or using built-in Django validation errors instead of raising and catching the broad Exception . 另外,您应该真正考虑使用自定义异常或使用内置的Django验证错误,而不是引发和捕获广泛的Exception

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM