擅长:python、mysql、java
<p>你的测试有两个问题</p>
<p>首先,在<code>feedback</code>函数中使用<code>input</code>,这将暂停测试,直到输入键为止。您可能应该模拟<code>input</code>。也可以考虑调用^ {< CD1> }不属于^ {< CD5> }(参见@ CHEPENER注释)。<p>
<p>其次,<code>from main import *</code>在这里不起作用(除了作为<a href="https://www.geeksforgeeks.org/why-import-star-in-python-is-a-bad-idea/" rel="noreferrer">bad style</a>),因为通过这种方式,您可以在测试模块中创建全局变量的副本-变量本身的更改不会传播到副本。您应该导入模块,以便访问模块中的变量</p>
<p>第三(这是从@chepner的答案中得出的,我没有注意到),您必须确保变量在测试开始时处于已知状态</p>
<p>以下是应该采取的措施:</p>
<pre><code>import unittest
from unittest import mock
import main # importing the module lets you access the original global variable
class TestMain(unittest.TestCase):
def setUp(self):
main.feedback = False # make sure the state is defined at test start
@mock.patch('main.input') # patch input to run the test w/o user interaction
def test_setFeedback(self, mock_input):
self.assertFalse(main.feedback)
main.setFeedback('y')
self.assertTrue(main.feedback)
</code></pre>