Mocking a global variable

后端 未结 4 1243
执念已碎
执念已碎 2020-12-24 11:27

I\'ve been trying to implement some unit tests for a module. An example module named alphabet.py is as follows:

import database

def length_letters(         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-24 11:44

    Try this:

    import unittests  
    import alphabet   
    from unittest.mock import patch   
    
    
    class TestAlphabet(unittest.TestCase): 
        def setUp(self):
            self.mock_letters = mock.patch.object(
                alphabet, 'letters', return_value=['a', 'b', 'c']
            )
    
        def test_length_letters(self):
            with self.mock_letters:
                self.assertEqual(3, alphabet.length_letters())
    
        def test_contains_letter(self):
            with self.mock_letters:
                self.assertTrue(alphabet.contains_letter('a'))
    

    You need to apply the mock while the individual tests are actually running, not just in setUp(). We can create the mock in setUp(), and apply it later with a with ... Context Manager.

提交回复
热议问题