Reputation: 39
For example, this class:
export class List<T> {
private _count: number;
private _items: Array<T>;
constructor() {
this._count = 0;
this._items = [];
}
get(index: number) {
return this._items[index];
}
add(item: T) {
this._items[this._count] = item;
this._count++;
}
}
This unit test in jasmine:
import { List } from './list';
describe( 'List', () => {
let testList: List<string>;
beforeEach(() => {
testList = new List<string>();
} );
it( 'get() method works', () => {
//how to test get() method without calling add() method?
testList.add( "string1" );
testList.add( "string2" );
testList.add( "string3" );
let s1: string = testList.get( 0 );
let s2: string = testList.get( 1 );
let s3: string = testList.get( 2 );
expect( s1 ).toBe( "string1" );
expect( s2 ).toBe( "string2" );
expect( s3 ).toBe( "string3" );
} );
}
I think, this is not unit test, but integration test, so how to write right unit test? I look at mock, but I don't know, how to use it in this case.
Upvotes: 0
Views: 64
Reputation: 2017
As the first option, you can fix state before testing a get method, i.e. add a check if the list is empty before adding items. As a second option, you can try to add a constructor with initial items, and a test for both empty constructor and constructor with items. Then you can rework your test without calling an add method.
But I think it's not so important because in any case, you will call other methods. Unit testing suggests isolating from other components like HTTP, database and so on.
Upvotes: 1