Thursday, 15 July 2010

unit testing - Understanding stubs, fakes and mocks. -



unit testing - Understanding stubs, fakes and mocks. -

i have started read professional test driven development c#: developing real world applications tdd

i have hard time understanding stubs, fakes , mocks. understand far, false objects used purpose of unit testing projects, , mock stub conditional logic it.

another thing think have picked mocks somehow related dependency injection, concept managed understand yesterday.

what not why utilize them. cannot seem find concrete examples online explains them properly.

can please explain me concepts?

as i've read in past, here's believe each term stands for

stub

here stubbing result of method known value, allow code run without issues. example, lets had following:

public int calculatedisksize(string networksharename) { // method things on network drive. }

you don't care homecoming value of method is, it's not relevant. plus cause exception when executed if network drive not available. stub result in order avoid potential execution issues method.

so end doing like:

sut.whencalled(() => sut.calculatedisksize()).returns(10);

fake

with false returning false data, or creating false instance of object. classic illustration repository classes. take method:

public int calculatetotalsalary(ilist<employee> employees) { }

normally above method passed collection of employees read database. in unit tests don't want access database. create false employees list:

ilist<employee> fakeemployees = new list<employee>();

you can add together items fakeemployees , assert expected results, in case total salary.

mocks

when using mock objects intend verify behaviour, or data, on mock objects. example:

you want verify specific method executed during test run, here's generic illustration using moq mocking framework:

public void test() { // arrange. var mock = new mock<isomething>(); mock.expect(m => m.methodtocheckifcalled()).verifiable(); var sut = new thingtotest(); // act. sut.dosomething(mock.object); // assert mock.verify(m => m.methodtocheckifcalled()); }

hopefully above helps clarify things bit.

edit: roy osherove know advocate of test driven development, , has info on topic. may find useful :

http://artofunittesting.com/

unit-testing mocking tdd stubs

No comments:

Post a Comment