【问题标题】:how to do Python unittest for while loop?如何为while循环做Python单元测试?
【发布时间】:2015-01-26 03:30:33
【问题描述】:

我写单元测试用例的时候,不知道怎么设计一个while循环的测试用例。有人可以给我一个指南来为下面的while循环代码sn-p编写一个单元测试用例吗?非常感谢。

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

【问题讨论】:

  • 为什么无论输入如何,“判断”函数总是返回相同的东西?我在这里看到的一个问题是没有可以捕获的输出行为(例如“返回结果”);此函数外部发生的唯一行为是打印语句。
  • 谢谢。如果 ret1 和 ret2 都不等于 0,while 循环是一个无限循环。所以没有特殊的输出。我已经更正了函数“判断”问题并添加了输出语句。

标签: python python-unittest


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多