How to AutoWire spring beans when using Mockito and Junit?
You are not mocking anything in your code. @InjectMocks sets a class where a mock will be injected.
Your code should look like this
public class PersonServiceTest {
@InjectMocks
PersonService personService;
@Mock
MockedClass myMock;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Mockito.doReturn("Whatever you want returned").when(myMock).mockMethod;
}
@Test()
public void testPerson() {
assertThat(personService.method, "what you expect");
}
Another solution is to use @ContextConfiguration
annotation with static inner configuration class like so:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class PersonServiceTest {
@Autowired
PersonService personService;
@Before
public void setUp() throws Exception {
when(personService.mockedMethod()).thenReturn("something to return");
}
@Test
public void testPerson() {
assertThat(personService.method(), "what you expect");
}
@Configuration
static class ContextConfiguration {
@Bean
public PersonService personService() {
return mock(PersonService.class);
}
}
}
Anyway, you need to mock something that the method you want to test uses inside to get desired behaviour of that method. It doesn't make sense to mock the service you're testing.