user902691
user902691

Reputation: 1159

Mock object is not injected

I try mock controler:

@RestController
public class SthControl {
    @Autowired
    private ObjRepo repo;    

    @RequestMapping(value = "/dosth", method = RequestMethod.POST, produces = "application/json")
    public ModelMap handleSth(@RequestParam("key") String key) { 
    final Logger logger = Logger.getLogger(getClass());

    logger.info("Is Mock "+ new MockUtil().isMock(repo));//return FALSE- is real object
logger.info("Key " + repo.loadByKey(key);//return NULL- always call real Method

Test Case:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml")
@WebAppConfiguration
public class SthControlTest {
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
protected WebApplicationContext wac;
private MockMvc mockMvc;

@Mock
private ObjRepo repo;

@InjectMocks
@Autowired
private SthControl contr;

@Before
public void setup() {

    MockitoAnnotations.initMocks(this);
    this.mockMvc = webAppContextSetup(this.wac).build();

    BasicConfigurator.configure();
}

@Test
public void testRegister() throws Exception {

    final UUID uuid = UUID.randomUUID();
    final String keyValue = "KeyVal";

    final Logger logger = Logger.getLogger(getClass());

    repo = Mockito.mock(ObjtRepo.class);
    Mockito.when(repo.loadByKey(keyValue)).thenReturn(new Obj(uuid, keyValue, TimeUtils.currentTimeSecond(), false));

Problem still exist if replace @Mock Annotation with this lines

repo = Mockito.mock(ObjRepo.class);
ReflectionTestUtils.setField(contr, "repo", repo, ObjRepo.class);
logger.info("Obj " + repo.loadByKey(keyValue).getId());//return correct object
logger.info("Mock Is "+new MockUtil().isMock(ReflectionTestUtils.getField(contr,"repo")));//True

Upvotes: 0

Views: 1673

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79857

There are two issues here.

  • You need to swap the lines this.mockMvc = webAppContextSetup(this.wac).build(); and MockitoAnnotations.initMocks(this);, otherwise the injection done by the Spring web application context setup will overwrite the injection done by Mockito. Always do the Spring injection first.

  • You need to remove the line repo = Mockito.mock(ObjtRepo.class); from testRegister, because this line replaces the value in repo with one that differs from the one you injected, so when you stub the new value, it won't affect the behaviour of SthControl.

Upvotes: 2

Related Questions