i am working in a django project and writing services to facilitate apis.in the services , i have class and class methods like this,
class ProductService(object):
def delete_product(self, product_id, deleting_user):
try:
product = Product.objects.get(pk=product_id)
except Product.DoesNotExist:
raise ObjectDoesNotExist(_('no product found for this id {}'.format(product_id)))
try:
deleting_user = Customer.objects.get(owner=deleting_user)
except Customer.DoesNotExist:
raise ValidationError(_('No owner found for this deleting user'))
i have write following unit test for this method,
def setUp(self):
self.product_service = ProductService()
self.wrong_id = 0
self.right_id = 1
self.right_user = _user
self.wrong_user = wrong_user
def test_raise_does_not_exist_error_for_wrong_product_id(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.wrong_id,
user=self.right_user
)
self.assertEqual(e.exception.message, 'no product found for this id {}'.format(wrong_id))
def test_raise_validtaion_error_for_wrong_deleting_user(self):
with self.assertRaises(ObjectDoesNotExist) as e:
self.product_service.delete_product(
self.product_id=self.right_id,
user=self.wrong_user
)
self.assertEqual(e.exception.message, 'No owner found for this deleting user')
so far so good, all the tests are OK!
but,say i have lots of test cases like this .that is, testing the 'errors' and if in future i have to change the error messages, then i have to change the test cases also, which could be a MESS, but on the other hand i also need to test the errors appropiately.
question is, how can i test the exceptions for different scenario?because the way i am testing, though it is ok for now,but for the future,it could be a mess,so i need some suggestions from you guys to handle this situation in an efficient way .