Prg2/unit testing
ไปยังการนำทาง
ไปยังการค้นหา
- This is part of Programming 2 2563
Clips
- Unit testing and mock objects: youtube
Codes
Using mocks to hide tkinter
File: test_maze.py
import unittest
from unittest.mock import MagicMock, patch
from dir_consts import *
from maze import Maze
class MazeTest(unittest.TestCase):
@patch('tkinter.PhotoImage')
def setUp(self, MockPhotoImage):
self.app = MagicMock()
self.maze = Maze(self.app, 800, 600)
self.MockPhotoImage = MockPhotoImage
def test_run(self):
self.assertFalse(self.maze.is_movable_direction(1, 1, DIR_UP))
self.assertTrue(self.maze.is_movable_direction(1, 1, DIR_DOWN))
self.assertFalse(self.maze.is_movable_direction(1, 1, DIR_LEFT))
self.assertTrue(self.maze.is_movable_direction(1, 1, DIR_RIGHT))
def test_eat_dot(self):
self.assertTrue(self.maze.has_dot_at(1, 1))
self.maze.eat_dot_at(1, 1)
self.assertFalse(self.maze.has_dot_at(1, 1))
Interaction testing with mocks
File: test_pacman.py
import unittest
from unittest.mock import MagicMock, patch
from dir_consts import *
from main import Pacman
class PacmanTest(unittest.TestCase):
@patch('tkinter.PhotoImage')
def setUp(self, MockPhotoImage):
self.app = MagicMock()
self.maze = MagicMock()
self.maze.piece_center.return_value = (20, 60)
self.pacman = Pacman(self.app, self.maze, 1, 1)
def test_eat_available_dot(self):
maze = self.maze
maze.is_at_center.return_value = True
maze.xy_to_rc.return_value = (1,1)
maze.has_dot_at.return_value = True
self.pacman.update()
self.assertTrue(maze.eat_dot_at.called)
def test_eat_no_dot(self):
maze = self.maze
maze.is_at_center.return_value = True
maze.xy_to_rc.return_value = (1,1)
maze.has_dot_at.return_value = False
self.pacman.update()
self.assertFalse(maze.eat_dot_at.called)