Skip to content

How to throw an exception on missed setup?

dvabuzyarov edited this page Nov 16, 2018 · 2 revisions

The idea is to make a general setup that will throw an exception. So when you access to a property or method it will throw the exception. But if you make another setup it will override the previous one. So you should get desired behavior.

export interface IDummy {
    property: string;
    method(value: number): string;
}

describe("the bug: the latest more specific setup does not override the previous one", () => {
    it("reproduce the bug", () => {
        const mock = new Mock<IDummy>();
        mock
            .setup(instance => It.Is((expression: ExpectedGetPropertyExpression) => true))
            .throws(new Error("setup is missed"))
            .setup(instance => instance.method(It.IsAny()))
            .returns(undefined);

        const actual = mock.object().method(1);
        expect(actual).toBeUndefined();
    });
});

you can create an internal class

export class MyMock<T> extends Mock<T> {
  constructor(name?: string) {
    super(name);
    this.setup(instance => It.Is(expression => true))
      .throws(new Error("setup is missed"));
  }
}

and use it instead of new Mock(). This approach would work with v2.7.0

Clone this wiki locally