How to use Dependency Injection without breaking encapsulation?

Many of the other answers hint at it, but I’m going to more explicitly say that yes, naive implementations of dependency injection can break encapsulation. The key to avoiding this is that calling code should not directly instantiate the dependencies (if it doesn’t care about them). This can be done in a number of ways. … Read more

How to restore a mock created with jest.mock()?

mockFn.mockRestore only works for a mock function created with jest.spyOn: const obj = { func: () => ‘original’ } test(‘func’, () => { const mock = jest.spyOn(obj, ‘func’); mock.mockReturnValue(‘mocked’); expect(obj.func()).toBe(‘mocked’); // Success! mock.mockRestore(); expect(obj.func()).toBe(‘original’); // Success! }) jest.spyOn wraps the original function and provides mockRestore as a way to restore the original function. jest.mock calls … Read more

How to terminate a program when it crashes? (which should just fail a unit test instead of getting stuck forever)

A summary from the answers by jdehaan and Eric Brown, as well as this question (see also this question): N.B. These solutions may affect other error reporting as well, e.g. failure to load a DLL or open a file. Option 1: Disable globally Works globally on the entire user account or machine, which can be … Read more

How to mock a function call on a concrete object with Moq?

You should use Moq to create your Mock object and set CallBase property to true to use the object behavior. From the Moq documentation: CallBase is defined as “Invoke base class implementation if no expectation overrides the member. This is called “Partial Mock”. It allows to mock certain part of a class without having to … Read more