Announcement Announcement Module
No announcement yet.
Help - Unit Testing with @Autowired private fields - most concise way ? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help - Unit Testing with @Autowired private fields - most concise way ?


    I have a class that I want to unit test. The class hasa n autowired PRIVATE member. This member is a service that does some db calls etc.

    I'm writing a unit test and obviously want to mock the autowired/injected member (using mockito).

    But, how do I plugin the mock into the class I want to test ?

    Obviously I can right a setter (hate polluting with silly code though) or I can just make the member 'package private' and simple set it directly from the test, but I would like to avoid this as it will show up as a violation on our static code analysis report (sonar)

    any ideas ?


  • #2
    Though I have not tried this by myself, but PowerMock has some features that would enable you to mock private, static methods. Also EasyMock with extension claim to have similar facility. Have you tried any of them ?


    • #3
      Remember that "private" in Java is not absolute. You can use reflection to get the "Field" object and call "setAccessible(true)". You can then use one of the "set" methods using the Field to set the private variable.


      • #4
        yes but I want to achieve this without having to write any low level infrastructure.

        Since Spring does it so easily, I wondered if there was a simple way to do it in a unit test without having to fire up the application context


        • #5
          You can achieve this very easily with mockito's Whitebox class.

          Whitebox.setInternalState( targetObject, "fieldName", mockObject );
          Where "targetObject" is an instance of the class you are testing, "fieldName" is the name of the field annotated with @Autowired, and "mockObject" is the mock service you want to inject.

          I hope it helps!



          • #6
            perfect - exactly what I was after

            thank you very much