- Mock -

Test double used to simulate an external dependency that receives information sent by the unit of code.
It allows to validate that information..
It can only exist ONE MOCK at most per test, given that it simulates an exit point and only one is verified per unit test
/** Interface tha defines an external dependency */
interface ILogger {
logInfo(info: string);
}
/** Real implementation for ILogger interface */
class RealLogger implements ILogger {
public logInfo(info: string) {
console.log(info);
}
}
/** Mock implementation to verify
* Calculator.add is logging properly */
class MockLogger implements ILogger {
/** Private field to store last logged info */
private receivedInfoToLog: string;
/** Method defined by ILogger interface */
public logInfo(info: string) {
/** Assign received info to this.receivedInfoToLog
* so we can later verify that Calculator.add sent
* the right info
*/
this.receivedInfoToLog = info;
}
/** Give access to validate latest logged info */
public get loggedInfo(): string {
return this.receivedInfoToLog;
}
}
class Calculator {
/** Costructor receiving an ILogger implementation */
constructor(private logger: ILogger) {}
public add(summand: number, otherSummand: number): number {
/** Uses received ILogger implementation to log info
* related to addition */
this.logger.logInfo(`Will add ${summand} and ${otherSummand}`);
return summand + otherSummand;
}
}
/** Test Beginning */
/** Initializes a MockLogger object to validate
* Calculator is properly logging data */
const mockLogger: MockLogger = new MockLogger();
/** Send MockLogger object to Calculator via constructor */
const calculator: Calculator = new Calculator(mockLogger);
/** Call add method to test that it's correctly logging the info */
calculator.add(4, 5);
/** Verify that the logged info is as expected */
mockLogger.loggedInfo === "Will add 4 and 5";
/** Test End */






