c# - How can I correctly unit test methods that depend on each other? -
consider code:
private readonly dictionary<type, component> _components = new dictionary<type, component>(); public component [type type] { { component component; _components.trygetvalue(type, out component); return component; } } public void addcomponent(component component) { _components.add(component.gettype(), component); }
as can see, addcomponent
adds private _components
variable. way test happening using indexer. that's fine, in order test indexer i'd have call addcomponent
too!
in other words, in unit tests indexer , addcomponent
, each test have call both of these methods. seems creating unnecessary coupling. if there bug in indexer, there no reason testaddcomponent
fail.
what best practice here? use reflection @ _components
? mocking? else?
well have 2 options:
- use reflection or mstest private accessor classes , set private field values during test.
- just don't worry , test exposed behaviour, if means test depends on other properties or method being tested elsewhere.
as can tell wording, choice #2 - should test exposed behaviour. in case exposed behaviour testing is:
- if use
addcomponent
added component should accessible through indexer - if use indexer, should able access components added through
addcomponent
in case obvious these pretty same thing, have 1 unit case / exposed behaviour test here. yes unit test covers 2 different things, shouldn't matter - aren't trying test each method / property behaves expected, rather want test each exposed behaviour works expected.
as alternative, suppose go option 1 , used private reflection check state of _components
ourselves. in case bevahour testing is:
- if use
addcomponent
added component should added_components
- if use indexer, should able access components in
_components
not testing internal behaviour of class (so if implementation changes tests fail, if class working expected), have doubled number of tests writing.
on top of that, increasing complexity of our tests increasing chance the tests themselves have bug - example if made mistake , in test 2. checked different private field? in case not have made more work ourselves, aren't testing actual behaviour want test!
Comments
Post a Comment