使用 assertRaise 测试异常消息 [英] Testing exception message with assertRaise

查看:40
本文介绍了使用 assertRaise 测试异常消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在条件引发自定义异常消息的函数内 assertRaise 异常.

I am trying to assertRaise the exception inside a function where a condition raises a custom exception message .

功能:

if not Cart.objects.filter(member=member).count():
    raise CartDoesNotExist("Cart Does Not Exist for Member: %s ( %id )." % (member.email,member.id))

现在,我能够成功地生成进入 raise 语句所需的条件.

Now , i am able to successfully produce the required condition to get to the raise statement.

所以,我的测试用例是这样的:

So , my testcase looks like this :

def Order_CartDoesNotExist(self):        
  self.assertRaises(CartDoesNotExist,Order.objects.create_order(member=self.member2,member_slot=self.memslot,order_type="Normal"))

当我运行测试时,输出为 Error .它给出了同样的错误 CartDoesNotExist.....

When i run the test , the output is an Error . It gives the same error CartDoesNotExist.....

所以我的问题是,如何引发这些异常?如何在我们的单元测试中涵盖这些情况?我不想逃避这些条件,因为它们很重要并增加代码覆盖率?

So my question is , how to raise these kind of exceptions ? How to cover these situations in our unittest? I do not want to escape these conditions as they are important and increase code coverage?

谢谢大家.

推荐答案

您的代码直接调用 create_order,这会引发异常.您需要更改它的调用方式.在 Python 2.7 中,你可以使用这个:

Your code is calling create_order directly, which raises the exception. You need to change how it is called. In Python 2.7, you can use this:

with self.assertRaises(CartDoesNotExist):
    Order.objects.create_order(member=self.member2, member_slot=self.memslot, order_type="Normal"))

这里的上下文管理器允许你直接调用你的代码,上下文管理器会为你处理异常.

Here the context manager allows you to call your code directly, and the context manager will handle the exception for you.

如果您运行的是 2.6 或更低版本:

If you are running with 2.6 or below:

self.assertRaises(CartDoesNotExist, Order.objects.create_order, member=self.member2, member_slot=self.memslot, order_type="Normal")

在这里,您不是在调用函数,而是将它连同它需要的参数一起传递给 assertRaises,然后 assertRaises 将调用代码并正确处理异常.

Here you aren't calling your function, you are passing it to assertRaises, along with the arguments it needs, and assertRaises will call the code and deal with the exception properly.

这篇关于使用 assertRaise 测试异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆