class Solution:
def addNums(self, a, b):
return a + b
test1 = Solution()
test1.addNums(5, 6)
以上是我的课程!使用简单的添加方法。
基本上,我想做的是为算法和数据结构/编程面试做准备,在这里我为每个输入创建实例,并想为实例编写单元测试。
这是我在下面尝试过的内容:
import unittest
class TestSolution(unittest.TestCase):
def test_addNums(self):
example = Solution()
self.assertEqual(example.addNums(9, 10), 19)
if __name__ == '__main__':
unittest.main()
不确定如何执行此操作,如果运行上面的代码,则会收到此错误消息:
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '/Users/abhishekbabuji/Library/Jupyter/runtime/kernel-eb5f1d39-4880-49a7-9355-bbddc95464ff'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.
SystemExit: True
我希望能够测试Solution
类的实例方法的返回值,在这种情况下为addNums(self, a, b)
答案 0 :(得分:2)
运行以下代码:
import unittest
class Solution:
def addNums(self, a, b):
return a + b
class TestSolution(unittest.TestCase):
def test_addNums(self):
example = Solution()
self.assertEqual(example.addNums(9, 10), 19)
if __name__ == '__main__':
unittest.main()
产生
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
编辑:以下内容应适用于jupyter。
import unittest
class Solution:
def addNums(self, a, b):
return a + b
class TestSolution(unittest.TestCase):
def test_addNums(self):
example = Solution()
self.assertEqual(example.addNums(9, 10), 19)
if __name__ == '__main__':
unittest.main(argv=['ignored', '-v'], exit=False)