我正在学习如何在Python中使用unittest进行单元测试。我想做的是在转数为负的情况下引发ValueError并显示一条消息,例如“转弯不能为负”。
我到目前为止编写的代码如下:
import unittest
from canvas import Game
class TestPlayer1(unittest.TestCase):
def setUp(self):
# Game objects
self.game_turn_0 = Game()
self.game_turn_5 = Game()
self.game_turn_negative = Game()
# values
self.game_turn_0.turn = 0
self.game_turn_5.turn = 5
self.game_turn_negative = -2
def test_get_turn(self):
self.assertEqual(self.game_turn_0.get_turn(), 0)
self.assertEqual(self.game_turn_5.get_turn(), 5)
with self.assertRaises(ValueError):
print('value error!')
if __name__ == '__main__':
unittest.main()
但是结果与预期不符,如您所见:
Testing started at 09:55 ...
C:\Users\oricc\PycharmProjects\practisingDrowing\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2019.2.3\helpers\pycharm\_jb_unittest_runner.py" --target test_canvas.TestPlayer1.test_get_turn
Launching unittests with arguments python -m unittest test_canvas.TestPlayer1.test_get_turn in C:\Users\oricc\PycharmProjects\practisingDrowing
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
value error!
Failure
Traceback (most recent call last):
File "C:\Users\oricc\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\Users\oricc\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 628, in run
testMethod()
File "C:\Users\oricc\PycharmProjects\practisingDrowing\test_canvas.py", line 23, in test_get_turn
print('value error!')
File "C:\Users\oricc\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 203, in __exit__
self._raiseFailure("{} not raised".format(exc_name))
File "C:\Users\oricc\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 135, in _raiseFailure
raise self.test_case.failureException(msg)
AssertionError: ValueError not raised
Assertion failed
Assertion failed
Ran 1 test in 0.034s
FAILED (failures=1)
Process finished with exit code 1
Assertion failed
Assertion failed
Assertion failed
Assertion failed
到目前为止,我已经观看了一些视频,阅读了python website上的文档,并阅读了一些帖子。我就可以掌握。
我的意思是,我无法在自己的情况下使用它。
有人可以向我解释这是如何工作的吗?谢谢
Class TestPlayer1(unittest.TestCase):
def setUp(self):
# Game objects
self.game_turn_0 = Game()
self.game_turn_5 = Game()
self.game_turn_negative = Game()
# values
self.game_turn_0.turn = 0
self.game_turn_5.turn = 5
self.game_turn_negative = -2
def test_get_turn(self):
self.assertEqual(self.game_turn_0.get_turn(), 0)
self.assertEqual(self.game_turn_5.get_turn(), 5)
with self.assertRaises(ValueError):
print('value error!')
如果名称 =='主':unittest.main()