[Python] How does one use pytest monkeypatch to patch a class

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to use pytest monkeypatch to mock a class which is imported into a separate module. Is this actually possible, and if so how does one do it? It seems like I have not seen an example for this exact situation. Suppose you have app with and imported class A in something.py

    from something import A #Class is imported

    class B :
    def __init__(self) :
    self.instance = A() #class instance is created

    def f(self, value) :
    return self.instance.g(value)


    inside my test.py I want to mock A inside B

    from something import B

    #this is where I would mock A such that
    def mock_A :
    def g(self, value) :
    return 2*value

    #Then I would call B
    c = B()
    print(c.g(2)) #would be 4


    I see how monkeypatch can be used to patch instances of classes, but how is it done for classes that have not yet been instantiated? Is it possible? Thanks!

    Continue reading...

Compartilhe esta Página