java - Getting around setter injection using mockito's @InjectMocks -


i have abstract class 2 map fields. 1 mock , inject object of subclass of abstractclass unit testing. other don't care about, has setter.

public abstract class abstractclass {     private map<string, object> maptomock;     private map<string, object> dontmockme;      private void setdontmockme(map<string, object> map) {         dontmockme = map;     } } 

when using @injectmocks, automatically tries inject in order: constructor, setter, field. checks if can inject in each of these places checking types, names if there multiple type possibilities. doesn't work me, because mocked maptomock injected dontmockme via setter. cannot edit abstract class. there way me around setter injection? thank in advance!

well corner case, automatic injection won't work in way mockito injection designed. mockito suffer shortcomings when there multiple fields same types.


so understand why doesn't work let's dive bit in way mockito performs injection :

  1. it try inject dependencies via constructor injection, if successes won't try following steps in order protect newly created instance eventual side effects.

  2. then if constructor injection did not happen (no arg constructor, or object instantiated), mockito matches between mocks , setters. has make choices happen automatically.

    1. if there mock of type a , 1 setter type a setter injection happen.

    2. if there either multiple mocks or setters of type a try find match using type , name of mock (usually @mock field name). if matches found injection happen.

  3. then if there still mocks left injection, field injection might happen, using same algorithm setter :

    1. if there mock of type a , 1 field type a field injection happen.

    2. if there either multiple mocks or field of type a try find match using type , name of mock (usually @mock field name). if matches found injection happen.


at moment code stuck @ stage 2.1 because there 1 mock available.

that being said current implementation of mockito there no real elegant solution, necessary write injection code. , wanted point mockito injection, if injection complex or weird, have write out ; writing boilerplate code best tool question current design.

mockito injection designed simple, straight designs.

in opinion, find wrong :

  1. to mock map, type don't own, might cause many problems.
  2. to mock single map in tested object, means test knows inner working of tested object.

it benefit design if refactor code , make collaborators emerge. clear dependencies/collaborators make injection clearer too. test should focus on asserting interactions collaborators not how data how implementation done, data should tested result given input.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -