2

I want on one method use mock eventService and in another real eventService.

   @Mock(name = "eventService")
        private EventService eventService;

        @InjectMocks
        private CandidateMenuController candidateMenuController = new CandidateMenuController();

How to write analog this code inside method. I have CandidateMenuController candidateMenuController as class field. But at one method I want to use specific eventService realization.

P.S I have not constructor and set get method for EventService

5
  • Could you just make two different CandidateMenuController objects, one with @InjectMocks and one without; then use whichever object is appropriate for each test? Commented Oct 9, 2013 at 11:47
  • Actually CandidateMenuController contain many different objects and its use. Commented Oct 9, 2013 at 11:49
  • So is there a setter for the one field that you want to be able to control the value of? Commented Oct 9, 2013 at 11:52
  • no, but @InjectMocks works and without it Commented Oct 9, 2013 at 11:53
  • 1
    You may have to either write such a setter, or use reflection. You can't tell @InjectMocks to be selective about which fields to inject. Commented Oct 9, 2013 at 11:56

2 Answers 2

1

As you do not have any setter method to set the value of EventService, you can use reflection to set the value for EventService:

@Test
public void testWithRealization() {
Field field = candidateMenuController.getClass().getDeclaredField("eventService");
field.set(candidateMenuController, new EventServiceImpl());

// Test Code
}
Sign up to request clarification or add additional context in comments.

Comments

1

Remove @MockitoJunitRunner from class and in method where you want to use mock do MockitoAnnotations.initMocks(this); In method where you want use specific implementation of EventService you have to create it manually by invoking constructor.

5 Comments

I have not understood How I pass my mock to CandidateMenuController instance?
Havent seen that you dont have setter available. I'm confused. Why you want to use specific EventService ? If you testing CandidateMenuController test it, and test implementations of EventService's in another test classes.
Maybe it is bad style? but I want to test it. initMocks inject mock, that annotated by @Mock But my mock creates inside method
It's not bad style. Sometimes it's the simplest way to avoid null pointer exceptions all the way through your tests.
Anyway you need either constuctor parameter or setter.. theres still reflection. Consider refactoring your code or create different test cases. Remember that testability of code is very important!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.