如何正确使用单元测试的 assertRaises() 与 NoneType 对象? [英] How to properly use unit-testing's assertRaises() with NoneType objects?

查看:27
本文介绍了如何正确使用单元测试的 assertRaises() 与 NoneType 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个简单的测试用例:

I did a simple test case:

def setUp(self):

  self.testListNone = None

def testListSlicing(self):

  self.assertRaises(TypeError, self.testListNone[:1])

我期待测试通过,但出现异常:

and I am expecting test to pass, but I am getting exception:

Traceback (most recent call last):

    self.assertRaises(TypeError, self.testListNone[:1])

TypeError: 'NoneType' object is unsubscriptable

我认为 assertRaises 会通过,因为 TypeError 异常会被提升?

推荐答案

如果你使用的是 python2.7 或更高版本你可以使用 assertRaises 用作上下文管理器并执行:

If you are using python2.7 or above you can use the ability of assertRaises to be use as a context manager and do:

with self.assertRaises(TypeError):
    self.testListNone[:1]

如果你正在使用 python2.6,除了到目前为止给出的方法之外,另一种方法是使用 unittest2这是 python2.6 的 unittest 新功能的后向端口,您可以使用上面的代码使其工作.

If you are using python2.6 another way beside the one given until now is to use unittest2 which is a back port of unittest new feature to python2.6, and you can make it work using the code above.

注意:我非常喜欢 unittest 的新功能(SkipTest、测试发现...),所以我打算尽可能多地使用 unittest2.我建议做同样的事情,因为 python2.6 <.

N.B: I'm a big fan of the new feature (SkipTest, test discovery ...) of unittest so I intend to use unittest2 as much as I can. I advise to do the same because there is a lot more than what unittest come with in python2.6 <.

这篇关于如何正确使用单元测试的 assertRaises() 与 NoneType 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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