Is there a way to use Python unit test assertions outside of a TestCase?

后端 未结 2 1991
说谎
说谎 2020-12-06 08:45

I need to create a fake helper class to be used in unit tests (injected into tested classes). Is there some way to use TestCase assertions in such class?

I would lik

相关标签:
2条回答
  • 2020-12-06 09:27

    You can create a instance of unittest.TestCase() and call the methods on that.

    import unittest
    
    tc = unittest.TestCase()
    tc.assertIsNotNone(a)
    

    On older Python versions (Python 2.7 and earlier, 3.0, 3.1) you need to you pass in the name of an existing method on the class TestCase class (normally it's passed the name of a test method on a subclass). __init__ will do in this case:

    tc = unittest.TestCase('__init__')
    tc.assertIsNotNone(a)
    

    However, you are probably looking for a good Mock library instead. mock would be a good choice.

    Another option is to use pytest, which augments assert statements to provide the same or more context as unittest.TestCase() assertion methods; you'd simply write assert a is not None.

    0 讨论(0)
  • 2020-12-06 09:42

    You can use Pytest or Nosetest. Though I'don't know if they have 'assertNotNull' function. I know they can use 'assert' simply for assertion. Or you can use something like assertpy or ptest, if you like, you can search for them on github.

    0 讨论(0)
提交回复
热议问题