user9585964
user9585964

Reputation:

AssertionError: ValueError not raised

init class exception does not raise exception to be identified by assetRaises()

When I create an instance separately for the class, the defined exception is printed properly

import unittest

class Circle:
    def __init__(self, radius):
        # Define the initialization method below
        self.radius = radius
        try :
          if  radius < 0 or radius > 1000 : raise ValueError
        except ValueError :
          print("radius must be between 0 and 1000 inclusive")

class TestCircleCreation(unittest.TestCase):
    def test_creating_circle_with_negative_radius(self):
        # Try Defining a circle 'c' with radius -2.5 and see 
        # if it raises a ValueError with the message
        # "radius must be between 0 and 1000 inclusive"
        with self.assertRaises(ValueError) as e:
            c = Circle(-2.5)
        self.assertEqual(str(e.exception),"radius must be between 0 and 1000 inclusive")

Gives error:

AssertionError: ValueError not raised

Upvotes: 0

Views: 7202

Answers (2)

khelwood
khelwood

Reputation: 59113

You're catching the exception inside __init__. Your test is asserting that the exception is thrown out from __init__, not caught inside it. Like this:

def __init__(self, radius):
    if radius < 0 or radius > 1000:
        raise ValueError("radius must be between 0 and 1000 inclusive")
    self.radius = radius

Upvotes: 1

L3viathan
L3viathan

Reputation: 27283

assertRaises only tests if an exception is thrown inside the context manager. You catch the exception and don't reraise it, so it is never seen by unittest.

Raising an exception and then immediately catching it doesn't make a ton of sense, either. Instead do:

class Circle:

    def __init__(self, radius):
        # Define the initialization method below
        self.radius = radius
        if radius < 0 or radius > 1000:
            raise ValueError("radius must be between 0 and 1000 inclusive")

Upvotes: 1

Related Questions