Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for mocking interfaces #76

Open
wants to merge 6 commits into
base: interfaces-mocking
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ Mocking library for TypeScript inspired by http://mockito.org/
## 1.x to 2.x migration guide
[1.x to 2.x migration guide](https://github.com/NagRock/ts-mockito/wiki/ts-mockito-1.x-to-2.x-migration-guide)


## Main features


* Strongly typed
* IDE autocomplete
* Mock creation (`mock`) (also abstract classes) [#example](#basics)
* Mock creation (`mock`) (also abstract classes and interfaces) [#example](#basics)
* Spying on real objects (`spy`) [#example](#spying-on-real-objects)
* Changing mock behavior (`when`) via:
* `thenReturn` - return value [#example](#stubbing-method-calls)
Expand All @@ -35,7 +36,7 @@ Mocking library for TypeScript inspired by http://mockito.org/

### Basics
``` typescript
// Creating mock
// Creating mock from a class
let mockedFoo:Foo = mock(Foo);

// Getting instance from mock
Expand All @@ -50,6 +51,43 @@ verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(5)).called();
```

### Create a mock from an interface

Mocking interfaxces works just the same as mocking classes, except you
must use the `imock()` function to create the mock.

```typescript
let mockedFoo:Foo = imock(); // Foo is a typescript interface
when(mockedFoo.getBar(5)).thenReturn('five');
```

It also works for properties.

```typescript
let mockedFoo:Foo = imock();
when(mockedFoo.bar).thenReturn('five');
```

For interface mocks, you can set the defauklt behviour for mocked properties that

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
For interface mocks, you can set the defauklt behviour for mocked properties that
For interface mocks, you can set the default behavior for mocked properties that

have no expectations set. They can behave eiter as a property, returning null, or
as a function, returning a function that returns null, or throw an exception.

```typescript
let mockedFoo1:Foo = imock(MockPropertyPolicy.Throw);
instance(mockedFoo1).bar; // This throws an exception, because there is no expectation set on the bar property

let mockedFoo2:Foo = imock(MockPropertyPolicy.Throw);
when(mockedFoo2.bar).thenReturn('five');
instance(mockedFoo2).bar; // Now this returns 'five', and no exception is thrown, because there is an expectation set on the bar property

let mockedFoo3:Foo = imock(MockPropertyPolicy.StubAsProperty);
instance(mockedFoo3).bar; // This returns null, because no expectation is set

let mockedFoo4:Foo = imock(MockPropertyPolicy.StubAsMethod);
instance(mockedFoo4).getBar(5); // This returns null, because no expectation is set
```


### Stubbing method calls

``` typescript
Expand Down
14 changes: 7 additions & 7 deletions src/MethodStubVerificator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,32 +29,32 @@ export class MethodStubVerificator<T> {
}

public times(value: number): void {
const allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.name, this.methodToVerify.matchers);
const allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.methodName, this.methodToVerify.matchers);
if (value !== allMatchingActions.length) {
const methodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify);
throw new Error(`Expected "${methodToVerifyAsString}to be called ${value} time(s). But has been called ${allMatchingActions.length} time(s).`);
}
}

public atLeast(value: number): void {
const allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.name, this.methodToVerify.matchers);
const allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.methodName, this.methodToVerify.matchers);
if (value > allMatchingActions.length) {
const methodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify);
throw new Error(`Expected "${methodToVerifyAsString}to be called at least ${value} time(s). But has been called ${allMatchingActions.length} time(s).`);
}
}

public atMost(value: number): void {
const allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.name, this.methodToVerify.matchers);
const allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.methodName, this.methodToVerify.matchers);
if (value < allMatchingActions.length) {
const methodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify);
throw new Error(`Expected "${methodToVerifyAsString}to be called at least ${value} time(s). But has been called ${allMatchingActions.length} time(s).`);
}
}

public calledBefore(method: any): void {
const firstMethodAction = this.methodToVerify.mocker.getFirstMatchingAction(this.methodToVerify.name, this.methodToVerify.matchers);
const secondMethodAction = method.mocker.getFirstMatchingAction(method.name, method.matchers);
const firstMethodAction = this.methodToVerify.mocker.getFirstMatchingAction(this.methodToVerify.methodName, this.methodToVerify.matchers);
const secondMethodAction = method.mocker.getFirstMatchingAction(method.methodName, method.matchers);
const mainMethodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify);
const secondMethodAsString = this.methodCallToStringConverter.convert(method);
const errorBeginning = `Expected "${mainMethodToVerifyAsString} to be called before ${secondMethodAsString}`;
Expand All @@ -73,8 +73,8 @@ export class MethodStubVerificator<T> {
}

public calledAfter(method: any): void {
const firstMethodAction = this.methodToVerify.mocker.getFirstMatchingAction(this.methodToVerify.name, this.methodToVerify.matchers);
const secondMethodAction = method.mocker.getFirstMatchingAction(method.name, method.matchers);
const firstMethodAction = this.methodToVerify.mocker.getFirstMatchingAction(this.methodToVerify.methodName , this.methodToVerify.matchers);
const secondMethodAction = method.mocker.getFirstMatchingAction(method.methodName, method.matchers);
const mainMethodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify);
const secondMethodAsString = this.methodCallToStringConverter.convert(method);
const errorBeginning = `Expected "${mainMethodToVerifyAsString}to be called after ${secondMethodAsString}`;
Expand Down
2 changes: 1 addition & 1 deletion src/MethodToStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ export class MethodToStub {
constructor(public methodStubCollection: MethodStubCollection,
public matchers: Matcher[],
public mocker: Mocker,
public name: string) {
public methodName: string) {
}
}
87 changes: 79 additions & 8 deletions src/Mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import {MockableFunctionsFinder} from "./utils/MockableFunctionsFinder";
import {ObjectInspector} from "./utils/ObjectInspector";
import {ObjectPropertyCodeRetriever} from "./utils/ObjectPropertyCodeRetriever";

export enum MockPropertyPolicy {
StubAsProperty,
StubAsMethod,
Throw,
}

export class Mocker {
protected objectInspector = new ObjectInspector();
private methodStubCollections: any = {};
Expand All @@ -18,7 +24,9 @@ export class Mocker {
private mockableFunctionsFinder = new MockableFunctionsFinder();
private objectPropertyCodeRetriever = new ObjectPropertyCodeRetriever();

constructor(private clazz: any, protected instance: any = {}) {
constructor(private clazz: any, policy: MockPropertyPolicy, protected instance: any = {}) {
this.mock.__policy = policy;

this.mock.__tsmockitoInstance = this.instance;
this.mock.__tsmockitoMocker = this;
if (_.isObject(this.clazz) && _.isObject(this.instance)) {
Expand All @@ -27,25 +35,41 @@ export class Mocker {
this.processFunctionsCode(this.clazz.prototype);
}
if (typeof Proxy !== "undefined") {
this.mock.__tsmockitoInstance = new Proxy(this.instance, this.createCatchAllHandlerForRemainingPropertiesWithoutGetters());
this.mock.__tsmockitoInstance = new Proxy(this.instance, this.createCatchAllHandlerForRemainingPropertiesWithoutGetters("instance"));
}
}

public getMock(): any {
if (typeof Proxy === "undefined") {
return this.mock;
}
return new Proxy(this.mock, this.createCatchAllHandlerForRemainingPropertiesWithoutGetters());
return new Proxy(this.mock, this.createCatchAllHandlerForRemainingPropertiesWithoutGetters("expectation"));
}

public createCatchAllHandlerForRemainingPropertiesWithoutGetters(): any {
public createCatchAllHandlerForRemainingPropertiesWithoutGetters(origin: "instance" | "expectation"): any {
return {
get: (target: any, name: PropertyKey) => {
const hasMethodStub = name in target;
if (!hasMethodStub) {
this.createPropertyStub(name.toString());
this.createInstancePropertyDescriptorListener(name.toString(), {}, this.clazz.prototype);
}
if (origin === "instance") {
if (this.mock.__policy === MockPropertyPolicy.StubAsMethod) {
if (name !== "then") {
// Don't make this mock object instance look like a Promise instance by mistake, if someone is checking
this.createMethodStub(name.toString());
this.createInstanceActionListener(name.toString(), {});
}
} else if (this.mock.__policy === MockPropertyPolicy.StubAsProperty) {
this.createPropertyStub(name.toString());
this.createInstancePropertyDescriptorListener(name.toString(), {}, this.clazz.prototype);
} else if (this.mock.__policy === MockPropertyPolicy.Throw) {
throw new Error(`Trying to read property ${name.toString()} from a mock object, which was not expected.`);
} else {
throw new Error("Invalid MockPolicy value");
}
} else if (origin === "expectation") {
this.createMixedStub(name.toString());
}
}
return target[name];
},
};
Expand Down Expand Up @@ -86,7 +110,6 @@ export class Mocker {
if (descriptor.get) {
this.createPropertyStub(name);
this.createInstancePropertyDescriptorListener(name, descriptor, obj);
this.createInstanceActionListener(name, obj);
} else if (typeof descriptor.value === "function") {
this.createMethodStub(name);
this.createInstanceActionListener(name, obj);
Expand Down Expand Up @@ -152,6 +175,54 @@ export class Mocker {
});
}

private createMixedStub(key: string): void {
if (this.mock.hasOwnProperty(key)) {
return;
}

// Assume it is a property stub, until proven otherwise
let isProperty = true;

Object.defineProperty(this.instance, key, {
get: () => {
if (isProperty) {
return this.createActionListener(key)();
} else {
return this.createActionListener(key);
}
},
});

const methodMock = (...args) => {
isProperty = false;

const matchers: Matcher[] = [];

for (const arg of args) {
if (!(arg instanceof Matcher)) {
matchers.push(strictEqual(arg));
} else {
matchers.push(arg);
}
}

return new MethodToStub(this.methodStubCollections[key], matchers, this, key);
};

const propertyMock = () => {
if (!this.methodStubCollections[key]) {
this.methodStubCollections[key] = new MethodStubCollection();
}

// Return a mix of a method stub and a property invocation, which works as both
return Object.assign(methodMock, new MethodToStub(this.methodStubCollections[key], [], this, key));
};

Object.defineProperty(this.mock, key, {
get: propertyMock,
});
}

private createPropertyStub(key: string): void {
if (this.mock.hasOwnProperty(key)) {
return;
Expand Down
4 changes: 2 additions & 2 deletions src/Spy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as _ from "lodash";
import {Mocker} from "./Mock";
import {Mocker, MockPropertyPolicy} from "./Mock";
import {RealMethod} from "./spy/RealMethod";
import {CallThroughMethodStub} from "./stub/CallThroughMethodStub";
import {MethodStub} from "./stub/MethodStub";
Expand All @@ -8,7 +8,7 @@ export class Spy extends Mocker {
private realMethods: { [key: string]: RealMethod };

constructor(instance: any) {
super(instance.constructor, instance);
super(instance.constructor, MockPropertyPolicy.StubAsProperty, instance);

if (_.isObject(instance)) {
this.processProperties(instance);
Expand Down
23 changes: 19 additions & 4 deletions src/ts-mockito.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,28 @@ import {StrictEqualMatcher} from "./matcher/type/StrictEqualMatcher";
import {MethodStubSetter} from "./MethodStubSetter";
import {MethodStubVerificator} from "./MethodStubVerificator";
import {MethodToStub} from "./MethodToStub";
import {Mocker} from "./Mock";
import {Mocker, MockPropertyPolicy} from "./Mock";
import {Spy} from "./Spy";

export {MockPropertyPolicy} from "./Mock";

export function spy<T>(instanceToSpy: T): T {
return new Spy(instanceToSpy).getMock();
}

export function mock<T>(clazz: { new(...args: any[]): T; } | (Function & { prototype: T }) ): T {
return new Mocker(clazz).getMock();
export function mock<T>(clazz: { new(...args: any[]): T; } | (Function & { prototype: T }), policy: MockPropertyPolicy = MockPropertyPolicy.StubAsProperty ): T {
return new Mocker(clazz, policy).getMock();
}

export function imock<T>(policy: MockPropertyPolicy = MockPropertyPolicy.StubAsMethod): T {
class Empty {}
const mockedValue = new Mocker(Empty, policy).getMock();

if (typeof Proxy === "undefined") {
throw new Error("Mocking of interfaces requires support for Proxy objects");
}
const tsmockitoMocker = mockedValue.__tsmockitoMocker as Mocker;
return new Proxy(mockedValue, tsmockitoMocker.createCatchAllHandlerForRemainingPropertiesWithoutGetters("expectation"));
}

export function verify<T>(method: T): MethodStubVerificator<T> {
Expand Down Expand Up @@ -65,7 +78,7 @@ export function capture<T0>(method: (a: T0) => any): ArgCaptor1<T0>;
export function capture(method: (...args: any[]) => any): ArgCaptor {
const methodStub: MethodToStub = method();
if (methodStub instanceof MethodToStub) {
const actions = methodStub.mocker.getActionsByName(methodStub.name);
const actions = methodStub.mocker.getActionsByName(methodStub.methodName);
return new ArgCaptor(actions);
} else {
throw Error("Cannot capture from not mocked object.");
Expand Down Expand Up @@ -128,6 +141,7 @@ export function objectContaining(expectedValue: Object): any {
export default {
spy,
mock,
imock,
verify,
when,
instance,
Expand All @@ -145,4 +159,5 @@ export default {
strictEqual,
match,
objectContaining,
MockPropertyPolicy,
};
2 changes: 1 addition & 1 deletion src/utils/MethodCallToStringConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import {MethodToStub} from "../MethodToStub";
export class MethodCallToStringConverter {
public convert(method: MethodToStub): string {
const stringifiedMatchers = method.matchers.map((matcher: Matcher) => matcher.toString()).join(", ");
return `${method.name}(${stringifiedMatchers})" `;
return `${method.methodName}(${stringifiedMatchers})" `;
}
}
5 changes: 4 additions & 1 deletion test/mocking.properties.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ describe("mocking", () => {
when(mockedFoo.sampleNumber).thenReturn(42);

// then
expect((mockedFoo.sampleNumber as any) instanceof MethodToStub).toBe(true);
expect((mockedFoo.sampleNumber as any).methodStubCollection).toBeDefined();
expect((mockedFoo.sampleNumber as any).matchers).toBeDefined();
expect((mockedFoo.sampleNumber as any).mocker).toBeDefined();
expect((mockedFoo.sampleNumber as any).methodName).toBeDefined();
});

it("does create own property descriptors on instance", () => {
Expand Down
Loading