我正在测试一个控制器的简单方法。问题是,控制器有一个服务,服务类有一个存储库。拥有所有这些,我想我需要模拟所有类。我是对的吗?
我可以轻松运行该应用程序,但是当我运行测试时,它会显示以下异常。如何绕过它来测试控制器的方法?
java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userRepositoryImpl':
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private org.hibernate.SessionFactory
com.myproject.repository.UserRepositoryImpl.sessionFactory;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in class path res
ource [main/my-servlet.xml]:
Invocation of init method failed; nested exception is
org.hibernate.HibernateException: Connection cannot be null when
'hibernate.dialect' not set
...
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private org.hibernate.SessionFactory
com.myproject.repository.UserRepositoryImpl.sessionFactory; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in class
....
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in class path
resource [main/my-servlet.xml]: Invocation of init method failed;
nested exception is org.hibernate.HibernateException: Connection
cannot be null when 'hibernate.dialect' not set
....
Caused by: org.hibernate.HibernateException: Connection cannot be
null when 'hibernate.dialect' not set
JUnit代码
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:main/my-servlet.xml"})
public class UserControllerTest {
@Autowired
WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void shouldReturnUsersViewName() throws Exception {
UserService mockedUsrSer = Mockito.mock(UserService.class);
UserController controller = new UserController(mockedUsrSer);
this.mockMvc.perform(get("/")).andExpect(view().name("users"));
}
控制器
private UserService userService;
@Autowired
public UserController(UserService userService) {
super();
this.userService = userService;
}
@RequestMapping(value = { "", "/"}, method = RequestMethod.GET)
public String showUsers(Model model) {
return "users";
}
服务
@Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
@Autowired
public UserServiceImpl(UserRepository userRepository){
this.userRepository = userRepository;
}
....
}
存储库
@Repository
public class UserRepositoryImpl implements UserRepository{
private SessionFactory sessionFactory;
@Autowired
public UserRepositoryImpl(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
...
}
我-servlet.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.myProject" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:2005/Test" />
<property name="username" value="jack" />
<property name="password" value="jack" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
depends-on="dataSource">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.myProject.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"
/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
更新
我在my-servlet.xml文件中注释掉了所有与hibernate相关的行,但测试返回了一个异常,如下所示:
No qualifying bean of type [org.hibernate.SessionFactory] found for dependency
答案 0 :(得分:2)
我认为您应该创建my-servlet.xml的精简版本并将其用于测试。它应该只对组件扫描控制器包。您还可以按如下方式将模拟UserService注入控制器。
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.myProject.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="userService" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.myproject.service.UserService" />
</bean>
另一种选择是使用standaloneSetup。
@RunWith(SpringJUnit4ClassRunner.class)
public class UserControllerTest {
@Mock
private UserService userService;
@InjectMocks
private UserController userController;
private MockMvc mockMvc;
@Before
public void setup() {
// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
}
答案 1 :(得分:0)
我同意user2953113的建议,这可能会奏效。但是,我尝试在单元测试中避免使用任何XML(功能测试是另一回事,但我不会在功能测试中模拟UserService)。我还没有使用过Spring MVC,但你能做到吗?在这种情况下,不确定你甚至需要SprintJUnit4ClassRunner。
public class UserControllerTest {
@Before
public void setup() {
UserService mockedUsrSer = Mockito.mock(UserService.class);
UserController controller = new UserController(mockedUsrSer);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
mockMvc.perform(get("/")).andExpect(view().name("users"));
}
}