Python unittest中assertRaises()检测负数回合ValueError失败求助
Let's break down what's going wrong in your code and how to fix it step by step.
First, Understand How assertRaises Works
The assertRaises context manager exists to verify that a specific piece of code triggers the expected exception. For it to work, you need to put the exact operation that should throw the exception inside the with block. If you don't run that code, assertRaises will fail because no exception was raised.
Issues in Your Current Code
Let's go through the problems one by one:
You Overwrote Your Game Object
InsetUp, you have this line:self.game_turn_negative = -2This replaces your
Gameinstance with an integer-2—so when you try to callget_turn()on it later, it would throw anAttributeError(since integers don't have that method). You meant to set theturnattribute of the existingGameobject:self.game_turn_negative.turn = -2You Didn't Trigger the Exception in the
assertRaisesBlock
Yourwith self.assertRaises(ValueError)block only contains aprintstatement. You never actually call the method that's supposed to throw the exception (get_turn()on the negative-turn game instance). That's why the test fails: no exception was raised during the block's execution.(Likely) Missing Validation in
Game.get_turn()
For the exception to be thrown at all, yourGameclass'sget_turn()method needs to include logic to check ifturnis negative and raise the error. If you haven't implemented that yet, add it:# In canvas.py class Game: def __init__(self): self.turn = 0 # Default value def get_turn(self): if self.turn < 0: raise ValueError('turn cannot be negative') return self.turn
Corrected Test Code
Here's the fixed version of your test class, with clear explanations:
import unittest from canvas import Game class TestPlayer1(unittest.TestCase): def setUp(self): # Initialize Game instances self.game_turn_0 = Game() self.game_turn_5 = Game() self.game_turn_negative = Game() # Set turn values correctly self.game_turn_0.turn = 0 self.game_turn_5.turn = 5 self.game_turn_negative.turn = -2 # Fixed: assign to the attribute, not the object def test_get_turn(self): # Test normal, non-negative cases self.assertEqual(self.game_turn_0.get_turn(), 0) self.assertEqual(self.game_turn_5.get_turn(), 5) # Test negative turn case: call get_turn() inside the assertRaises block with self.assertRaises(ValueError) as context: self.game_turn_negative.get_turn() # Optional: Verify the exception message is correct (makes test more robust) self.assertEqual(str(context.exception), 'turn cannot be negative') if __name__ == '__main__': unittest.main()
How This Works
- The
with self.assertRaises(ValueError)block wraps the call toget_turn()on the negative-turn game. When that method runs, it will throw theValueError, whichassertRaisescatches and validates. - Using
context.exceptionlets you check that the error message matches exactly what you expect, ensuring your validation logic is working as intended.
内容的提问来源于stack exchange,提问作者Techoplite

