断言失败后,如何继续单元测试?

2024-06-02 07:03:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在testdpropy中执行第二个断言,不管第一个是否通过。如果不在第一个assert周围放置try/except块,我如何做到这一点?代码如下:

class BlockTests(unittest.TestCase):
    def setUp(self):
        self.city1 = City(1, "New York")
        self.city2 = City(2, "Boston")

    def tearDown(self):
        self.city1 = None

    def testIdProperty(self):
        self.assertEqual(2, self.city1.id_city, "Assertion Error!") #This assert might fail
        self.assertEqual(2, self.city2.id_city, "Assertion Error!") #Execute this anyway

    def testIdGetter(self):
        self.assertEqual(1, self.city1.get_id_city(), "Error!")

目前,如果第一个assert失败,测试用例会立即报告失败,而第二个assert永远不会运行。在


Tags: selfidcitydeferrorassert断言try
3条回答

如果您正在执行多个检查,并且您始终希望运行所有检查,则最简单的解决方案就是将它们分成多个测试,并使每个测试用例只有一个检查:

class BlockTests(unittest.TestCase):
    def setUp(self):
        self.city1 = City(1, "New York")
        self.city2 = City(2, "Boston")

    def tearDown(self):
        self.city1 = None

    def testIdPropertyCity1(self):
        self.assertEqual(2, self.city1.id_city, "Assertion Error!") #This assert might fail

    def testIdPropertyCity2(self):
        self.assertEqual(2, self.city2.id_city, "Assertion Error!") #Execute this anyway

    def testIdGetter(self):
        self.assertEqual(1, self.city1.get_id_city(), "Error!") 

使用^{}怎么样?在

def testIdProperty(self):
    with self.assertRaises(SomeError):
        self.assertEqual(2, self.city1.id_city, "Assertion Error!")
    self.assertEqual(2, self.city2.id_city, "Assertion Error!")

从您的测试来看,您似乎在尝试测试类Cityid属性。因此,您可以测试您在setUp中定义的两个实例是否具有正确的值集-类似于您所做的:

def testIdProperty(self):
    self.assertEqual(1, self.city1.id_city, "Fail if City1 does not have id 1")
    self.assertEqual(2, self.city2.id_city, "Fail if City2 does not have id 2")

现在,当你运行这个测试时,它应该通过。如果有一天您破坏了代码,这两个断言中有一个失败,那么您希望在运行测试并修复它时看到它。在

但是,如果出于某种原因,您不希望这些断言暂时失败,直到您稍后回来完成测试,那么您可以这样跳过该测试:

^{pr2}$

编辑:好,如果您想禁止失败断言中的错误,请不要尝试/除非在您需要的每个位置执行。最好在测试类之外编写一个泛型函数:

def silent_assert(func, *args, **kwargs):
    try:
        func(*args, **kwargs)
    except Exception as exc:
        print exc.message

让这个调用您的assert,这样它将运行代码,并且只有在失败时才会静默地打印错误:

def testIdProperty(self):
    silent_assert(self.assertEqual, 1, self.city1.id_city, "City1 does not have id 1")
    silent_assert(self.assertEqual, 2, self.city2.id_city, "City2 does not have id 2")

您将能够调用它的任何断言,并传递每个人接受的任意数量的参数。不知道隐藏这样的错误是否是个好主意,我从来没有这样做过,但那只是我,每个人都有他们的组织风格!在

相关问题 更多 >