简体   繁体   English

使用assertRaise测试异常消息

[英]Testing exception message with assertRaise

I am trying to assertRaise the exception inside a function where a condition raises a custom exception message . 我试图在一个条件引发自定义异常消息的函数内断言异常。

Function: 功能:

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

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"))

When i run the test , the output is an Error . 当我运行测试时,输出是一个错误。 It gives the same error CartDoesNotExist..... 它给出了相同的错误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? 我不想逃避这些条件因为它们很重要并且增加了代码覆盖率?

Thank you all. 谢谢你们。

Your code is calling create_order directly, which raises the exception. 您的代码直接调用create_order,这会引发异常。 You need to change how it is called. 你需要改变它的调用方式。 In Python 2.7, you can use this: 在Python 2.7中,您可以使用:

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. 在这里,上下文管理器允许您直接调用代码,上下文管理器将为您处理异常。

If you are running with 2.6 or below: 如果您使用2.6或更低版本运行:

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

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. 这里你没有调用你的函数,你将它传递给assertRaises,以及它需要的参数,assertRaises将调用代码并正确处理异常。

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

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