I have spent two full days now trying to understand the difference between unit testing and handling exception, but I can't get it.
Things I have understood (or I think I have):
- Unit testing tests functions and classes
- can be done with the unittest module in Python
- exceptions are non-syntax errors
- exceptions can be handled with try/except statements inside the main .py file
- exceptions come in different types
- never raise a general exception, always specify the type
Things I don't get:
- when and what is worth to unit test
if I can use - and if it's good or bad practice - try/except statements in unit testing
if it's true that both aim to achieve the exact same goal, and namely to handle exceptions in a more 'readable' manner
if they are two different things
if they have to be used together
For example, I have a Game class with a turn attribute. What I want to do is to test that the turn value is a positive number, even though I know it will never be negative, I just want to use this to practice with testing.
In the real world, should I just use a try/except statement in the main code, or should I unit test it anyway.
I have a main file with this code:
import pygame
# initialize
pygame.init()
# set the window
window_size = (800, 800)
game_window = pygame.display.set_mode(window_size)
pygame.display.set_caption('My Canvas')
# define colours
colours = {
'black': (0, 0, 0),
'white': (255, 255, 255),
'gold': (153, 153, 0),
'green': (0, 180, 0)
}
class Game:
def __init__(self):
self.turn = 0
self.player = None
self.winner = None
# getter methods
def get_turn(self):
try:
assert self.turn >= 0
except ValueError:
print('turn number must be positive')
def get_player(self):
return self.player
def get_winner(self):
return self.winner
# setter methods
def set_turn(self, turn):
self.turn = int(turn)
def set_player(self, player):
self.player = player
def set_winner(self, winner):
self.winner = winner
and a test.py file open right next to it, so I can write test straight away, with this code:
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.turn = -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):
self.game_turn_negative.get_turn()
if __name__ == '__main__':
unittest.main()
Can I have some clarifications, please?
Thank you