Mocking a global variable

后端 未结 4 1238
执念已碎
执念已碎 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:50

    Variables can be patched as follows:

    from mock import patch
    @patch('module.variable', new_value)    
    

    For example:

    import alphabet
    from mock import patch
    @patch('alphabet.letters', ['a', 'b', 'c'])
    class TestAlphabet():
    
        def test_length_letters(self):
            assert 3 == alphabet.length_letters()
    
        def test_contains_letter(self):
           assert alphabet.contains_letter('a')
    

提交回复
热议问题