Python 如何对一个简单的类进行单元测试?
我有一个python类:Python 如何对一个简单的类进行单元测试?,python,unit-testing,Python,Unit Testing,我有一个python类: class Animal: def __init__(self, name, energy=100): self.name = name self.energy = energy 我需要使用模块unittest创建一些简单的测试。例如,测试能量是否大于零或 名称是字符串类型。我该怎么做?(我还没有经验) 这些类型的东西通常不会用单元测试进行测试,而是用\uuuuu init\uuuu方法中的 class Ani
class Animal:
def __init__(self, name, energy=100):
self.name = name
self.energy = energy
我需要使用模块unittest创建一些简单的测试。例如,测试能量是否大于零或
名称是字符串类型。我该怎么做?(我还没有经验) 这些类型的东西通常不会用单元测试进行测试,而是用
\uuuuu init\uuuu
方法中的
class Animal:
def __init__(self, name, energy=100):
if not isinstance(name, str):
raise TypeError("name should be a string")
if energy <= 0:
raise ValueError("energy has to be more than 0")
self.name = name
self.energy = energy
或者使用内置模块:
这些听起来不像是针对这段代码的合理单元测试。它们可能是其他代码的合理单元测试,但不是此代码。非常简单和简单-例如,您不能单元测试
name
是否是字符串,因为name
根本不是来自此代码。@user2357112supportsMonica他可以在执行这些更改的情况下测试Energy的默认值,然后,您可以使用单元测试来验证,例如,当为能量
提供负值/零值时,是否会引发值错误
。
import pytest
import Animal
def test_init_ok():
animal = Animal("name", 100)
assert animal.name == "name"
assert animal.energy == 100
def test_init_bad_name():
with pytest.raises(TypeError):
animal = Animal(123, 100)
def test_init_bad_energy():
with pytest.raises(ValueError):
animal = Animal("name", 0)
with pytest.raises(ValueError):
animal = Animal("name", -100)
import unittest
import Animal
class TestAnimal(unittest.TestCase):
def test_init_ok(self):
animal = Animal("name", 100)
self.assertEqual(animal.name, "name")
self.assertEqual(animal.energy, 100)
def test_init_bad_name(self):
with self.assertRaises(TypeError):
animal = Animal(123, 100)
def test_init_bad_energy(self):
with self.assertRaises(ValueError):
animal = Animal("name", 0)
with self.assertRaises(ValueError):
animal = Animal("name", -100)