Mockito:结合@Autowired和@Mock

时间:2016-11-09 14:40:08

标签: java unit-testing spring-mvc mockito powermockito

我在Spring Web模型 - 视图 - 控制器(MVC)框架应用程序中使用Mockito(在MIT许可下发布的Java的开源测试框架)进行了这个junit测试

我有这个测试:

@RunWith(MockitoJUnitRunner.class)
public class DeviceCatalogueControllerTest {


    @InjectMocks
    private DeviceCatalogueController controller;

    @InjectMocks
    protected SessionHelper sessionHelper;

    @Mock
    private MessageSource messageSource;

    @Mock
    protected CataloqueService cataloqueService;

    @Autowired
    protected ApplicationDao applicationDao;

    @Before
    public void setUpTest() {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void testInitFormGet() throws Exception {

        System.out.println  ("SessionHelper sessionHelper --> " + sessionHelper);

        //controller.initFormGet(searchForm, localeParam, request, response, model, locale)
        controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE));
        }

但运行测试时 applicationDao 为空

1 个答案:

答案 0 :(得分:1)

您的测试类完全不了解Spring。要在单元测试中使用Spring,您必须使用正确的注释@RunWith(SpringJUnit4ClassRunner.class),而不是现在使用的@RunWith(MockitoJUnitRunner.class)

然后在@Before方法中,您可以通过调用Mockito来初始化MockitoAnnotations.initMocks(this);模拟

您的测试类可以重新编码为:

@ContextConfiguration(locations = {"classpath:/application-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class DeviceCatalogueControllerTest {


    @InjectMocks
    private DeviceCatalogueController controller;

    @InjectMocks
    protected SessionHelper sessionHelper;

    @Mock
    private MessageSource messageSource;

    @Mock
    protected CataloqueService cataloqueService;

    @Autowired
    protected ApplicationDao applicationDao;

    @Before
    public void setUpTest() {
        MockitoAnnotations.initMocks(this);
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void testInitFormGet() throws Exception {

        System.out.println("SessionHelper sessionHelper --> " + sessionHelper);

        //controller.initFormGet(searchForm, localeParam, request, response, model, locale)
        controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE));
    }
}

注意:在application-context.xml

中使用@ContextConfiguration(locations = {"classpath:/application-context.xml"})的正确xml路径