Results 1 to 6 of 6

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

  1. #1

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

    Hi,

    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 ?

    thanks

  2. #2

    Default

    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. #3
    Join Date
    Jan 2006
    Location
    Seattle, Washington
    Posts
    467

    Default

    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. #4

    Default

    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. #5

    Default

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

    Code:
    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!


    nicolas.loriente

  6. #6

    Default

    perfect - exactly what I was after

    thank you very much

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •