Unittest mock a .NET with pythonnet


Is there a way to mock a .NET library loaded with clr.AddReference(), without the presence of the actual dll?

My code:

import clr

import MyDeviceDriver

class MyClass:
    def __init__(self):
        self.__deviceAPI = MyDeviceDriver.Create()

My Unittest code:

    def test_func(self):
        my_object = MyClass()


>       self.__deviceAPI = MyDeviceDriver.Create()
E       System.Runtime.SomeLibrary.COMException: Retrieving the COM class factory for component with CLSID {9F8D4F16-0F61-4A38-98B3-1F6F80F11C87} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

I'd like to unittest MyClass without needing the library in the path or any classes registered in the registry.

Is there a way to do that? I tried patching with various types of errors. I tried patching AddReference, MyDeviceDriver with no success. Essentially from python's unittest docs it appears that "patch" needs the original library available.

asked on Stack Overflow Mar 1, 2021 by Noam Bonnie • edited Mar 2, 2021 by maanijou

1 Answer


Since it is Python, can't you do

import MyCode
import unittest

class DriverMock(): pass

MyCode.MyDeviceDriver = DriverMock

def test_func():
    my_object = MyClass()
answered on Stack Overflow Mar 1, 2021 by LOST

User contributions licensed under CC BY-SA 3.0