How to assert output with nosetest/unittest in python?

后端 未结 12 1451
野趣味
野趣味 2020-11-28 02:56

I\'m writing tests for a function like next one:

def foo():
    print \'hello world!\'

So when I want to test this function the code will b

12条回答
  •  Happy的楠姐
    2020-11-28 03:32

    I'm only just learning Python and found myself struggling with a similar problem to the one above with unit tests for methods with output. My passing unit test for foo module above has ended up looking like this:

    import sys
    import unittest
    from foo import foo
    from StringIO import StringIO
    
    class FooTest (unittest.TestCase):
        def setUp(self):
            self.held, sys.stdout = sys.stdout, StringIO()
    
        def test_foo(self):
            foo()
            self.assertEqual(sys.stdout.getvalue(),'hello world!\n')
    

提交回复
热议问题