模拟对象没有注入

时间:2014-03-25 21:07:37

标签: unit-testing spring-mvc testing junit mockito

我尝试模拟控制器:

@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

测试用例:

@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));

如果用此行替换@Mock Annotation

,问题仍然存在
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

1 个答案:

答案 0 :(得分:2)

这里有两个问题。

  • 您需要交换行this.mockMvc = webAppContextSetup(this.wac).build();MockitoAnnotations.initMocks(this);,否则Spring Web应用程序上下文设置完成的注入将覆盖Mockito完成的注入。始终先进行弹簧注射。

  • 您需要从repo = Mockito.mock(ObjtRepo.class);删除行testRegister,因为此行会将repo中的值替换为与您注入的值不同的值,因此当您存根时新值,它不会影响SthControl

  • 的行为