Home > Enterprise >  Unittest only passing single value rather than getting multiple values
Unittest only passing single value rather than getting multiple values

Time:04-28

The title might be a little confusing, but I need to figure out the correct syntax for getting both the first_name and the last_name from the python decorator and inserting it into my unittest.

class Person:

    def __init__(self, first_name = '', last_name = ''):

        self.first_name = first_name
        self.last_name = last_name

    @property
    @getting first name
    def first_name(self):
        return self._first_name
    
    @first_name.setter
    #setting first name
    def first_name(self, first_name):
        self._first_name = first_name.capitalize()

    @property
    #getting last name
    def last_name(self):
        return  self._last_name

    @last_name.setter
    #setting last name
    def last_name(self, last_name):
        self._last_name = last_name.capitalize()

and here is my unittest snippet

class TestPerson(unittest.TestCase, Person):

    def test_first_name(self):
        testFirst = Person('James')
        self.assertEqual(testFirst.first_name, 'James')

    def test_last_name(self):
        testLast = Person('Jonah')
        #assertionerror is thrown here
        #AssertionError: '' != 'Jonah'
        # Jonah
        self.assertEqual(testLast.last_name, 'Jonah')

While Person('James') works, I know it doesn't work for Person('Jonah') as it only passes the first name. The issue is, that none of my poking around seems to make it work correctly. I cannot outright go Person.last_name('Jonah') as the property decorator isn't callable, and tinkering with _last_name, get, getattribute do not work here either.

If anyone knows the correct syntax for making this unittest pass, please send it my way! I seriously cannot figure it out.

Thanks in advance!

CodePudding user response:

The __init__ method of your class accepts keyword parameters for the different attributes, in your tests pass the parameters as keywords. If you don't use keyword arguments then the first positional argument will be passed to first_name since it is the first keyword argument defined

def test_first_name(self):
    testFirst = Person(first_name='James')
    ...

def test_last_name(self):
    testLast = Person(last_name='Jonah')
    ...
  • Related