gpt4 book ai didi

java - 我是否需要模拟服务和存储库类来测试 Controller 的简单方法?

转载 作者:行者123 更新时间:2023-12-02 04:21:39 24 4
gpt4 key购买 nike

我正在测试我的 Controller 的一个简单方法。问题是, Controller 有一个服务,而服务类有一个存储库。有了这一切,我想我需要模拟所有的类。我说得对吗?

我可以轻松运行该应用程序,但是当我运行测试时,它显示以下异常。我怎样才能绕过它来测试 Controller 的方法?

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

}

Controller

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;
}
...
}

my-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

最佳答案

我认为您应该创建 my-servlet.xml 的精简版本并使用它进行测试。它应该只对 Controller 包进行组件扫描。您还可以向 Controller 注入(inject)模拟 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();

}
}

关于java - 我是否需要模拟服务和存储库类来测试 Controller 的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32706166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com