0

I have:

class MyClassA:
    def __init__(...):
        do some stuff
        create object attributes


def myfunc:
    get required data
    create MyClassA object(s)
    store MyClassA object(s) in a list
    return(list of MyClassA object(s))

Now I'm writing unittests for myfunc like this:

import unittest

class Test_myfunc(unittest.TestCase):
    sample_data = ...
    expected_result = ??
    self.assertEqual(myfunc(sample_data), expected_result)

What do I set expected_result to be? For the test to pass it should be a list of objects, but then it should have the same instances that are created when I pass the sample data into myfunc. If I create another instance of MyClassA in the unittest then it will obviously fail because the instances would be different. I would like to validate that for each object in the output list from myfunc the attributes match the sample_data. What is the right way to do this?

PS: I hope my question is clear.

2 Answers 2

2

You shouldn't care that your expected result and returned result contain distinct instances, only that they contain equal instances. Just manually create the instances you expect myfunc to create, and make sure that your class has an appropriate definition of __eq__ to do the comparisons.

Sign up to request clarification or add additional context in comments.

Comments

0

Test_myfunc is probably overloaded, consider breaking it down into more manageable chunks.

For example, some test case definitions might be:

test_myfunc_returns_list
test_myfunc_list_items_are_instanceof_MyClassA
test_myfunc_contains_MyClassA_with_attributes

The idea is to keep test cases simple, so that failures are easier to understand and the error messages are informative.

The last test is where you can assert that the sample data in an individual object is present. If you wanted, you could also create more definitions with the same idea - with different cases for different MyClassA scenarios.

1 Comment

@ Alex Forbes - thanks for the feedback. Yes the unit test does appear overloaded. I'll split it up into smaller/simpler tests.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.