有没有办法在 TestCase 之外使用 Python 单元测试断言? [英] Is there a way to use Python unit test assertions outside of a TestCase?

查看:23
本文介绍了有没有办法在 TestCase 之外使用 Python 单元测试断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个在单元测试中使用的假帮助类(注入到测试类中).有没有办法在这样的类中使用 TestCase 断言?

I need to create a fake helper class to be used in unit tests (injected into tested classes). Is there some way to use TestCase assertions in such class?

我想将断言用于 Fake 类执行的一些常见检查.类似的东西:

I would like to use the assertions for some common checks performed by the Fake class. Something like:

class FakeFoo(object):

  def do_foo(self, a, b):
    assertNotNull(a)
    ...

推荐答案

您可以创建 unittest.TestCase() 的实例并调用其上的方法.

You can create a instance of unittest.TestCase() and call the methods on that.

import unittest

tc = unittest.TestCase()
tc.assertIsNotNone(a)

在较旧的 Python 版本(Python 2.7 及更早版本、3.0、3.1)上,您需要在 TestCase 类(通常为它在子类上传递了测试方法的名称).__init__ 在这种情况下会做:

On older Python versions (Python 2.7 and earlier, 3.0, 3.1) you need to you pass in the name of an existing method on the class TestCase class (normally it's passed the name of a test method on a subclass). __init__ will do in this case:

tc = unittest.TestCase('__init__')
tc.assertIsNotNone(a)

然而,您可能正在寻找一个好的模拟库.mock 将是一个不错的选择.

However, you are probably looking for a good Mock library instead. mock would be a good choice.

另一种选择是使用 pytest,它增强assert 语句 提供与 unittest.TestCase() 断言方法相同或更多的上下文;你只需写assert a is not None.

Another option is to use pytest, which augments assert statements to provide the same or more context as unittest.TestCase() assertion methods; you'd simply write assert a is not None.

这篇关于有没有办法在 TestCase 之外使用 Python 单元测试断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆