How do you show an error message when a test does not throw an expected exception?

前端 未结 2 936
傲寒
傲寒 2021-01-27 08:02

I am new to python. I wanted to test if my code throws an exception. I got the code from here: How do you test that a Python function throws an exception?

import         


        
2条回答
  •  难免孤独
    2021-01-27 08:57

    As of python 3.3, assertRaises can be used as a context manager with a message:

    import unittest
    
    def sayHelloTo(name):
        print("Hello " + name)
    
    class MyTestCase(unittest.TestCase):
        def test1(self):
            person = "John"
            with self.assertRaises(Exception, msg="My insightful message"):
                sayHelloTo(person)
    
    if __name__ == "__main__":
        unittest.main()
    

    Results in

    Hello John
    F
    ======================================================================
    FAIL: test1 (__main__.MyTestCase)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "r.py", line 10, in test1
        sayHelloTo(person)
    AssertionError: Exception not raised : My insightful message
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.001s
    
    FAILED (failures=1)
    

提交回复
热议问题