Reputation: 381
I need help. I want to test an exception case in my test, so I have to mock 'add()' method. How can I test it?
my model:
class CourseGroup(models.Model):
students = models.ManyToManyField(
"users.User",
blank=True,
related_name="course_groups_students",
)
my method:
def add_student_to_group(student: User):
course_groups = CourseGroup.objects.all()
for group in course_groups:
try:
group.students.add(student)
except Exception as ex:
sentry_message(
title="some title",
message="some message",
)
my test
I'm trying to do it like this, but it's not working.
class AddStudentToGroupTestCase(TestCase):
@classmethod
def setUp(cls):
cls.course_group_1 = CourseGroupFactory()
cls.course_group_2 = CourseGroupFactory()
cls.course_group_3 = CourseGroupFactory()
cls.student = StudentFactory()
@patch("users.service.sentry_message")
@patch("users.models.CourseGroup.students.add")
def test_add_student_with_exception(self, mock_add, mock_sentry_message):
mock_add.side_effect = Exception("ERROR")
# call
with self.assertRaises(Exception):
add_student_to_group(student=self.student)
mock_sentry_message.assert_called()
I get an error:
AttributeError: <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x7f643f2afd10> does not have the attribute 'add'
Has anyone encountered something like this?
Upvotes: 0
Views: 20