c# - Adding Virtual Keyword When Testing Legacy Code -
i adding tests gnarly legacy code in order have confidence enough refactor it. 1 of issues whoever wrote code made no attempt make code testable (given never wrote single unit test!)
a common issue there no interfaces, 11-level-deep inheritance chain. using rhino mocks isolate class under test dependencies, mocking class, not interface, can stub read-only property if has virtual
keyword.
my current thinking add virtual
keyword property. there no plan add further objects existing dependency chain , allow tests written.
are arguments against adding virtual
keyword, or acceptable compromise in order tests in?
example code...
in test class:
var someclassstub = mockrepository.generatestub<someclass>(); someclassstub.stub(s => s.someproperty).return("test");
in someclass:
public virtual string someproperty { { return somedependency.somemethod(); } }
the primary argument against adding virtual
misrepresents intentions. virtual
keyword signals derived classes expect property may overridden.
i not use virtual
, mock dependency following:
var mockeddependency = mockrepository.generatemock<idependency>(); mockeddependency.expect(x => x.somemethod()) .returns("whatever test dictates"); var target = new someclass(mockeddependency); mockeddependency.verifyallexpectations();
then inject newly created overloaded constructor, following:
public someclass(idependency dependency) : base() { this.somedependency = dependency; }
Comments
Post a Comment