如何测试抛出异常的函数

时间:2012-12-01 09:09:36

标签: python exception

  

可能重复:
  How do you test that a Python function throws an exception?

我必须进行白盒和黑盒测试,所以我想知道如何测试一个异常的函数,比如这个

class validator_client():

    def validate_client(self,client):
        erori=[]
        if client.get_identitate()=="":
            erori.append("Nu exista ID!")
        if client.get_nume()=="":
            erori.append("Nu exista nume!")
        if (client.get_filme_inchiriate()!="da" ) and (client.get_filme_inchiriate()!="nu") :
            erori.append("Campul 'Filme inchiriate' completat gresit!")
        if len(erori)>0:
            raise ValidatorException(erori)

我已经阅读了一些关于assertRises()但我无法使用此方法导入模块,在stackowerflow上找到了这个:

from testcase import TestCase

import mymod

class MyTestCase(TestCase):
    def test1(self):
        self.assertRaisesWithMessage(SomeCoolException,
                                     'expected message',
                                      mymod.myfunc)

但我无法使其发挥作用。

1 个答案:

答案 0 :(得分:2)

这是一个工作示例,它是python文档中的简化版本。它会检查random.shuffle是否会引发TypeError例外。

import random, unittest

class TestSequenceFunctions(unittest.TestCase):
    def test_shuffle(self):
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

unittest.main()