如何为 while 循环做 Python 单元测试?
how to do Python unittest for while loop?
我在写单元测试用例的时候,不知道如何设计while循环的测试用例。有人可以指导我为下面的 while 循环代码片段编写单元测试用例吗?非常感谢。
def judge(arg):
flag = 1 if arg > 15 else 0
return flag
def while_example(a,b):
output = "NOK"
while True:
ret1 = judge(a)
ret2 = judge(b)
if ret1 == 0 and ret2 == 0:
print "both a and b are OK"
output = "OK"
break
else:
print "both a and b are not OK"
a =- 1
b =- 1
return output
我已经克服了这个单元测试问题,下面是我的答案
import unittest
import sys
from StringIO import *
from while_loop import *
from mock import *
class TestJudge(unittest.TestCase):
def testJudge_1(self):
self.assertEqual(judge(16), 1)
def testJudge_2(self):
self.assertEqual(judge(15), 0)
class TestWhile(unittest.TestCase):
def test_while_1(self):
judge = Mock(side_effect=[0,0])
out = StringIO()
sys.stdout = out
a = while_example(1, 1)
output = out.getvalue().strip()
self.assertEqual(output, "both a and b are OK")
def test_while_2(self):
judge = Mock(side_effect=[1,0])
out = StringIO()
sys.stdout = out
a = while_example(18, 12)
output = out.getvalue().strip()
self.assertEqual(output, 'both a and b are not OK\nboth a and b are OK')
if __name__ == "__main__":
unittest.main()
我在写单元测试用例的时候,不知道如何设计while循环的测试用例。有人可以指导我为下面的 while 循环代码片段编写单元测试用例吗?非常感谢。
def judge(arg):
flag = 1 if arg > 15 else 0
return flag
def while_example(a,b):
output = "NOK"
while True:
ret1 = judge(a)
ret2 = judge(b)
if ret1 == 0 and ret2 == 0:
print "both a and b are OK"
output = "OK"
break
else:
print "both a and b are not OK"
a =- 1
b =- 1
return output
我已经克服了这个单元测试问题,下面是我的答案
import unittest
import sys
from StringIO import *
from while_loop import *
from mock import *
class TestJudge(unittest.TestCase):
def testJudge_1(self):
self.assertEqual(judge(16), 1)
def testJudge_2(self):
self.assertEqual(judge(15), 0)
class TestWhile(unittest.TestCase):
def test_while_1(self):
judge = Mock(side_effect=[0,0])
out = StringIO()
sys.stdout = out
a = while_example(1, 1)
output = out.getvalue().strip()
self.assertEqual(output, "both a and b are OK")
def test_while_2(self):
judge = Mock(side_effect=[1,0])
out = StringIO()
sys.stdout = out
a = while_example(18, 12)
output = out.getvalue().strip()
self.assertEqual(output, 'both a and b are not OK\nboth a and b are OK')
if __name__ == "__main__":
unittest.main()