JavaPhySel
JavaPhySel

Reputation: 81

using Uniitest.TestResult.wasSuccessful() to chqcke if test has passed or not

In Python unittest framework we want to do some check after every test case. If it was succesful or not and if its not succussful we want to do some action.

I am trying to explore Unittest.TestResult.wasSuccessful(), but it returns 'True' even of test has passed. Here is example and output. As my test_addNumbers has failed it should return False

import unittest
class SampleClass(unittest.TestCase):
    result = unittest.TestResult()

    def setUp(self):
        print 'setup'

    def tearDown(self):
        print self.result.wasSuccessful()
        print 'tearDown'

    def test_addNumbers(self):
        a = 10
        b = 20
        c = a + b
        print c
        self.assertEqual('fo'.upper(), 'FOO')

    def test_addNumbers_new(self):
        p = 20
        q = 20
        r = p + q
        print r
        return r  

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(SampleClass)
    unittest.TextTestRunner(verbosity=1).run(suite)

Output:

import unittest setup 30

Failure Expected :'FO' Actual :'FOO'

Traceback (most recent call last): File "C:\Users\a4tech\Documents\WorkSpace\Vanilla_Python.git\Kiran_Test\SampleUnitTest.py", line 19, in test_addNumbers self.assertEqual('fo'.upper(), 'FOO') AssertionError: 'FO' != 'FOO'

True

tearDown

setup

40

True

tearDown

Upvotes: 1

Views: 2112

Answers (1)

Humbalan
Humbalan

Reputation: 717

A TestResult instance is returned by the TestRunner.run() method for this purpose

(Found in https://docs.python.org/2/library/unittest.html#unittest.TestResult).

So you should change your last line in the code to

test_result = unittest.TextTestRunner(verbosity=1).run(suite)

and then evaluate test_result. Its value then is

<unittest.runner.TextTestResult run=2 errors=0 failures=1>

Upvotes: 2

Related Questions