期望Python assertRaises()失败,但测试总是通过

时间:2015-03-26 23:20:48

标签: python unit-testing python-unittest

我正在尝试进入TDD的实践,所以我一直在尝试从Python的unittest模块开始。我写过一个我完全希望失败的测试,但它总是通过!以下是测试代码:

def test_file_not_found_exception(self):
    invalid_config = "Testing/invalidExperiment.xml"
    experiment_with_invalid_config = MyClass(invalid_config)
    self.assertRaises(OSError, experiment_with_invalid_config.run_experiment())

我的班级定义如下:

class MyClass:
    def __init__(self, experiments, output_directory = ".")
        self._experiments = experiments
        self._output_directory = output_directory
    def run_experiment(self):
        try:
            x = 2 # dummy statement
        except OSError:
            print "Experiment file not found"
        except:
            print "Unexpected Error"

我认为try块应该总是正确执行,所以我不知道为什么我的unittest继续传递。我对Python中的OOP很新,所以我可能会犯一个非常明显的错误...另外,如果我在run_experiment()方法的try-except块中捕获异常,那么assertRaises()调用是否可以工作? / p>

1 个答案:

答案 0 :(得分:1)

您正在调用函数MyClass.run_experiment并将其输出传递给self.assertRaises,因此在它无法引发时无法正确注册错误。

错误示例:

import unittest
class MyClass(object): 
    def __init__(self, config): 
        pass
    def run_experiment(self): pass

class MainTest(unittest.TestCase): 
    def test_file_not_found_exception(self):
        invalid_config = "Testing/invalidExperiment.xml"
        experiment_with_invalid_config = MyClass(invalid_config)
        self.assertRaises(OSError, experiment_with_invalid_config.run_experiment())

if __name__ == "__main__":
    unittest.main()

正确:

with self.assertRaises(OSError): 
    experiment_with_invalid_config.run_experiment() 

self.assertRaises(OSError, experiment_with_invalid_config.run_experiment)