gpt4 book ai didi

java - 如何正确测试此方法?(junit)

转载 作者:行者123 更新时间:2023-11-29 05:37:16 26 4
gpt4 key购买 nike

我有这个方法:

@Transactional
@Service("vacancyService")
public class VacancyService {

public boolean delete(Integer id) {
Vacancy vacancy = vacancyDao.findById(id);
return vacancy != null && vacancyDao.remove(vacancy);
}
...
}

我想测试上面的方法。

实现vacancyDao.remove(vacancy):

  public boolean remove(Vacancy vacancy) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
if (vacancy == null) {
return false;
}

int result = session.createQuery("delete from Vacancy where id = :id")
.setInteger("id", vacancy.getId()).executeUpdate();
return result > 0;

}

我的测试类:

@TransactionConfiguration(defaultRollback = false)
@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
public class VacancyServiceTest extends AbstractTransactionalJUnit4SpringContextTests{

@Test
public void testDeleteMethod(){
//what I can write here?
}

我不知道如何测试这个方法。你能帮帮我吗?

更新

在这里添加我的配置文件:

BeanConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<!-- Включаем опцию использования конфигурационных аннотаций (@Annotation-based configuration)-->
<context:annotation-config />


<context:component-scan base-package="com.epam.hhsystem.jpa" />
<context:component-scan base-package="com.epam.hhsystem.services" />

<!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
<import resource="data.xml" />

</beans>

数据.xml:

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<!-- Настраивает управление транзакциями с помощью аннотации @Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />

<!-- Менеджер транзакций -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- Непосредственно бин dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://10.16.9.52:1433;databaseName=hhsystemTest;"
p:username="userNew"
p:password="Pass12345" />

<!-- Настройки фабрики сессий Хибернейта -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:test/hibernate.cfg.xml</value>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create-drop</prop> -->
</props>
</property>
</bean>

</beans>

如果您需要更多详细信息,我会在此处发布。

最佳答案

由于提供了服务类单元测试,下面是对 Dao 类 remove 方法进行单元测试的方法

public class vacancyDaoTest {

@InjectMocks
VacancyDao vacancyDao = new VacancyDao();

@Mock
Session session;

@Mock
Query query;

@Mock
SessionFactory sessionFactory;

@BeforeClass
public void setup(){
MockitoAnnotations.initMocks(this);
when(sessionFactory.getSession()).thenReturn(session);
}



@Test
public void testRemove(){
String hql = "delete from Vacancy where id = :id";
when(session.createQuery(hql)).thenReturn(query);
when(query.setInteger(eq("id"), anyInt())).thenReturn(query);
when(query.executeUpdate).thenReturn(1);
int result = vacancyDao.remove(new Vacancy());
verify(session).createQuery(any(String.class));
verify(query).setInteger(eq("id"), anyInt());
verify(query).executeUpdate();
assertNotNull(result);
assertTure(result);


}



}

关于java - 如何正确测试此方法?(junit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19029779/

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