vendredi 20 novembre 2015

Multiple instances of mock object

I was looking for a way to mock multiple instances of the same class. Tried the solution from How to get many instances of one Mock object and that does work. However, I also want to specify properties and behavior for each new instance of the mocked class in my test case. Didn't find the answer to that yet.

Example:

class A:
    def __init__(self, name):
        self.name = name

    def get_name(self):
        print("hi " + self.name)
        return self.name


class B:
    def __init__(self):
        self.a_map = {}

    def get_a(self, name):
        a = A(name)
        self.a_map[a] = a.get_name()


with mock.patch('__main__.A') as mockA:
    b = B()
    mockA.side_effect = mock.Mock
    for i in range(5):
        b.get_a('person' + str(i))
    print(b.a_map)
    assert len(b.a_map) == 5

How can I change this code so that when an instance of mockA is created, it also sets the name property of the instance? e.g. I need the output for this code to be something like:

{<Mock id='13609360'>: 'person0', <Mock id='13608720'>: 'person1', <Mock id='13610128'>: 'person2', <Mock id='13609744'>: 'person3', <Mock id='13608976'>: 'person4'}

Aucun commentaire:

Enregistrer un commentaire