Sam's Surf Shop (Unit Testing Project)

Hey all! I have a question regarding the Sam’s Surf Shop Project Here

import surfshop import unittest class shopTests(unittest.TestCase): def setUp(self): self.cart = surfshop.ShoppingCart() def test_add(self): for i in range(2,5): with self.subTest(i=i): message = self.cart.add_surfboards(i) self.assertEqual(message, f'Successfully added {i} surfboards to cart!') self.cart = surfshop.ShoppingCart()

We define self.cart in the beginning of the project, but when we run a subtest we have to define it again at the end. Why is this? I would have never figured it out, but I looked at the solution to see how they did it.

The problem here is that methods like setUp() and tearDown() that normally run with each new test actually don’t do so within subtests. The extra line at the end recreates a fresh ShoppingCart object for each subtest so that changes caused by the add_surfboards() method don’t persist between each test

ah, this makes total sense! Thank you so much for pointing that out. I guess I skimmed over that part of the lesson haha.

Even if I defined self.setUp inside the loop (below with) I still have TooManyBoardsError at value of 4 (( Whats wrong? Of couse I have expected failure test
PS When I additionally insert self.setUp before with - everything is just fine.

1 Like