如何为while循环做Python unittest?

时间:2015-01-26 03:30:34

标签: python python-unittest

当我编写单元测试用例时,我不知道如何设计while循环的测试用例。 有人可以给我一个guid为下面的循环代码片段写一个单元测试用例吗? 非常感谢。

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

1 个答案:

答案 0 :(得分:0)

我已经克服了这个单元测试问题,下面是我的答案

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()