Mockito不会在春季mvc控制器测试中嘲笑

时间:2013-12-20 14:17:36

标签: spring-mvc mockito

我有控制器

@Controller
public class AuthorController {

    @Autowired
    private AuthorDAO authorDao;

    @RequestMapping("/authors")
    public String showAuthor(@RequestParam String name, ModelMap model) {
        Author author = authorDao.findByName(name);
        model.addAttribute("author", author);

        return "authors";
    }

}

我为它写了测试

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

    private static final String JACK_C = "Jack C.";

    @Autowired
    AuthorController controller;

    @Test
    public void testShowAuthor() {

        Author expectedAuthor = new Author();

        AuthorDAO daoMock = mock(AuthorDAO.class);

        when(daoMock.findByName(JACK_C)).thenReturn(expectedAuthor);

        ModelMap model = new ModelMap();

        String view = controller.showAuthor(JACK_C, model);
        assertEquals("View name is incorrect","authors", view);

        assertSame(expectedAuthor, model.get("author"));
        verify(daoMock).findByName(JACK_C);
    }

}

测试应用context.xml中:

<context:annotation-config />
    <context:component-scan base-package="com.github.futu" />   

     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
        <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property 
        name="url" value="jdbc:mysql://localhost:3306/blog" /> <property name="username" 
        value="blogger" /> <property name="password" value="blogger" /> </bean>

    <bean id="com.github.futu.dao.AuthorDAO" class="com.github.futu.dao.impl.AuthorDAOXml"/> 

    <bean id="com.github.futu.dao.PostDAO" class="com.github.futu.dao.impl.PostDAOXml" />       

    <bean id="validator" class="com.github.futu.validator.PostValidator" /> 

但真正的dao被称为。我错过了什么?

1 个答案:

答案 0 :(得分:1)

你在这里创建一个模拟

AuthorDAO daoMock = mock(AuthorDAO.class);

与注入测试类的控制器完全无关

@Autowired
AuthorController controller;

当然,自动装配的AuthorDao目标将来自您的XML配置

@Autowired
private AuthorDAO authorDao;

理想情况下,您将更改XML配置,只生成一个@Controller bean,并使用您的模拟为其添加一个setter,以便在测试中设置AuthorDao