Reputation: 693
I'm new with Spring and Mockito testing. I couldn't find answer to my problem on stackoverflow.
I have the following classes:
@EnableScheduling
@Service
public class ServiceEx {
private Queue<Object> tasks = new ConcurrentLinkedQueue();
public void addItem(Object task) {
tasks.add(task);
}
@Scheduled(fixedRate = 30000)
public void executePendingTask() {
tasks.remove();
}
public void drop() {
tasks.clear();
}
public boolean isEmpty() {
return tasks.isEmpty();
}
}
@Controller
@RequestMapping("/drop")
public class ControllerEx {
private ServiceEx service;
@Inject
public ControllerEx(ServiceEx service) {
this.service = service;
}
@RequestMapping(method = RequestMethod.GET)
public String dropTasks(Model model) {
service.drop();
return "redirect:/home";
}
}
And my testing class looks like :
public class ControllerTest {
@Inject
private ServiceEx service;
@InjectMocks
private ControllerEx controller;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void test() {
service.add(task1);
service.add(task2);
this.mockMvc.perform(get("/drop")).andExpect(status().is3xxRedirection());
assertTrue(service.isEmpty());
}
}
My problem is that service is null in both ControlleEx and ControllerTest and i don't want to mock it. I tried several annotations, but didn't find which one to use.
What have i done wrong?
Upvotes: 0
Views: 1107
Reputation: 118
Looking at your code you seem to be mixing unit tests with integration tests.
MockMvc is usually used to do integration tests starting at the controller level. this means that you need a configured and started applicationContext to successfully use that. If that's what this test class is supposed to do then I don't see the use of Mocks, unless you wire them in the application context, your controller won't use them.
If you want to do integration testing, but want to Mock or stub out certain functionality (which in my opinion should only be done because of dependencies on external systems) you should think about wiring some stubs in your applicationContext for this test instead of trying to use Mockito for this.
Also keep in mind that by default, the applicationContext is re-used to run all your tests, which could mean that stubbing for one test could affect an other.
Upvotes: 1