Monday, 15 June 2015

c# - Move Method for Mocking? -



c# - Move Method for Mocking? -

i have unit tests calls applicationshouldbeinstalled(app) create sure it's working correctly. actual production code, below, calls method, doesn't accidentally install app. however, nil preventing developer removing line of code check done. , unit tests wouldn't grab because tests testing applicationshouldbeinstalled(app) method, , not installapplications() method.

i can't phone call installapplications() test code because effort install application. installapplication(app) method in same class, not class can mock interface. there way create sure installapplications() performs check? guess move applicationshouldbeinstalled(app) class , mock it, i'm moving code sake of testing/mocking. there improve way?

public void installapplications() { foreach (app app in this._apps) { if (!applicationshouldbeinstalled(app)) { continue; } installapplication(app); } }

the mocking alternative this. container homecoming real implementation when running live, , mock when running test.

public void installapplications() { foreach (app app in this._apps) { if (!applicationshouldbeinstalled(app)) { continue; } container.resolve<iinstaller>().installapplication(app); } }

yes, remove code controls policy of whether or not application should installed code handles installation. allow test both pieces of code in isolation , gain confidence each doing require. go far have 3 collaborators here. code controls loop, code controls validating against policy, , code performs install. 3 pieces, independently testable, easier verify.

foreach (var app in this._apps) { if (!applicationinstallationpolicyprovider.caninstall(app)) // can mocked away { continue; } applicationinstaller.install(app); // can mocked away }

i think key when said in question "you cannot run install code in test." should of import verify loop will phone call installation code when required. should plenty motivation seek isolate it, whether or not take grade might prefer.

c# unit-testing mocking

No comments:

Post a Comment