python-3.x - Python 中的测试驱动开发

标签 python-3.x unit-testing testing

我如何编写测试,以测试打印我们给它的范围的默认行为(方法的)?以下是我的尝试。粘贴我的实现文件和测试用例文件中的代码。

`class FizzBuzzService:
def print_number(self, num):
    for i in range(num):
        print(i, end=' ')

import unittest
from app.logic import FizzBuzzService


class FizzBuzzServiceTestCases(unittest.TestCase):
    def setUp(self):
    """
    Create an instance of fizz_buzz_service
    """
    self.fizzbuzz = FizzBuzzService()

    def test_it_prints_a_number(self):
    """
    Test for the default behavior of printing the range that we give 
    fizz_buzz_service
    """
    number_range = range(10)
    self.assertEqual(self.fizzbuzz.print_number(10), print(*number_range))

最佳答案

至少对我来说,TDD 既是关于测试的,也是关于寻找好的设计的。如您所见,测试输出之类的东西很困难。

这样的打印被称为副作用 - 简单地说,它正在做一些事情,而不仅仅是基于方法的输入参数。我的解决方案是减少 print_number 的副作用,然后像那样测试它。如果您需要打印它,您可以编写另一个更高层的函数来打印,即 print_number 的输出,但除此之外不包含任何有意义的逻辑,这实际上不需要测试。这是一个示例,您的代码已更改为没有副作用(这是几种可能的替代方案之一)

class FizzBuzzService:
def print_number(self, num):
    for i in range(num):
        yield i

import unittest


class FizzBuzzServiceTestCases(unittest.TestCase):
    def setUp(self):
    """
    Create an instance of fizz_buzz_service
    """
    self.fizzbuzz = FizzBuzzService()

def test_it_prints_a_number(self):
    """
    Test for the default behavior of printing the range that we give 
    fizz_buzz_service
    """
    number_range = range(10)
    output = []
    for x in self.fizzbuzz.print_number(10):
        output.append(x)
    self.assertEqual(range(10), output)

关于python-3.x - Python 中的测试驱动开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887064/

相关文章:

javascript - 在不关闭 Selenium/Splinter 中的驱动程序的情况下更改代理设置

Python 流提取

c++ - Jenkins 和 cFix 单元测试 (C++)

unit-testing - httptest.NewRequest 与 http.NewRequest : which one to use in tests and why?

python - 有没有办法用pytest沙箱测试执行,尤其是文件系统访问?

python - 在 Matplotlib 中显示绘图之前获取空刻度标签

python - 是否可以将 django 用户帐户绑定(bind)到一个特定的工作站?

c# - 如何在 C# 项目中构建单元测试引用

ruby-on-rails - 为什么我在一个模型上的 rspec Rails 测试需要 10 分钟?! (Rails 3.2/rspec 2/Guard/spork)

r - 支持向量机训练插入符错误 kernlab 类概率计算失败;返回 NA