坚持/提交在 Spring JPA JUnit 的测试环境中不起作用

2024-04-20

我正在尝试设置基本的 JPA 插入测试。但数据库中没有保存任何内容。 数据库是Postgresql。 Hibernate 用作持久性提供者。

提前谢谢了。

@Entity
public class Currency {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;    

    @Column
    private String code;

    @Column
    private String name;
...
}

CRUD 类:

@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Transactional(propagation = Propagation.REQUIRED)
public class CRUDServiceBean implements CRUDService {

      @PersistenceContext(type = PersistenceContextType.EXTENDED)
      private EntityManager entityManager;

       public EntityManager getEntityManager() {
            return entityManager;
        }

        public <T extends BaseEntity> T persistAndCommit(T t) {
            entityManager.persist(t);
            entityManager.refresh(t);
            entityManager.getTransaction().commit();
            return t;
        }

        ...
        ...
}

所有测试的基类:

@RunWith(SpringJUnit4ClassRunner.class)
@Configurable(autowire = Autowire.BY_NAME)
@ContextConfiguration(locations = { "classpath:context-test.xml" })
public class BaseTest {
}

测试类:

public class CurrencyCreateTest extends BaseTest {

    @Autowired
    CRUDService crudService;

    @Test
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createCurrency() throws Exception {
        Currency currency = new Currency();
        currency.setCode("EUR");
        currency.setName("Euro");
        currency = crudService.persistAndCommit(currency);
    }
}

上下文测试.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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-4.0.xsd">         

    <context:component-scan base-package="com.chartinvest"/>

    <bean id="contextApplicationContextProvider" class="com.chartinvest.util.ApplicationContextProvider"></bean> 


    <!-- the parent application context definition for the springapp application -->

    <!-- dataSource -->
    <bean id="dataSourceFinance" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName"><value>org.postgresql.Driver</value></property>
      <property name="url"><value>jdbc:postgresql://localhost/db_finance_test</value></property>
      <property name="username"><value>postgres</value></property>
      <property name="password"><value>xxxxxxxx</value></property>
    </bean> 

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />       
    </bean>  

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="mypersistenceunit" />
        <property name="dataSource" ref="dataSourceFinance" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
            </bean>
        </property>
        <property name="jpaPropertyMap">
            <map>
                <entry key="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            </map>
        </property>
    </bean>

    <!-- Enable the configuration of transactional behavior based on annotations -->       
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

如果您的测试成功通过并且没有收到任何异常,那么请使用@TransactionConfiguration(defaultRollback=false)每个测试类或使用@回滚(假)每个测试方法。 事务测试将在 Spring 测试上下文中默认回滚。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
  "test-context.xml"})
@TransactionConfiguration(defaultRollback=false)
@Transactional
public class SampleCrudTest {

    @Autowired
    private SampleCrud sampleCrud;

    @Before 
    public void onSetUpInTransaction() throws Exception {
        //Populate Test Data
    }


    @Test
    public void registerSample() {

        Sample sample = new Sample("foo");
        sampleCrud.save(sample);
        assertNotNull(sample.getId());
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

坚持/提交在 Spring JPA JUnit 的测试环境中不起作用 的相关文章

随机推荐

  • Java中一个字符是1字节还是2字节?

    我认为 java 中的字符是 16 位 如建议的那样java doc http download oracle com javase tutorial java nutsandbolts datatypes html 字符串不也是这样吗 我
  • Highcharts Marimekko 图表刷新

    下面的脚本构建了一个基本的 Marimekko 图表 其中 x 值是累积的 作为一种令人兴奋的绘制数据的方式 这是非常棒的 http jsfiddle net Guill84 1o926coh http jsfiddle net Guill
  • 带指针的数组长度

    C 中如何仅使用指针获取数组长度 我知道选项卡名称是指向第一个元素的指针 但下一步是什么 你不能做到 您需要将数组长度与数组指针一起传递 或者需要使用容器对象 例如std vector
  • System.getenv 没有获取 ~/.bash_profile 中定义的变量

    这是文件 bash profile 中的一行 export MESSAGE Hello World 我想访问系统变量MESSAGE在Java中 System getenv MESSAGE 不起作用 bash profile 文件仅源自登录
  • ASP.NET Identity,持久性 cookie - 是内置的类似的东西吗?

    我们正在使用Cookie身份验证提供者并希望实施 记住账号 我们的应用程序中的功能将像这样工作 无论是否 记住账号 复选框是否被选中 令牌过期时间应始终设置为 30 分钟 SlidingExpiration 打开 如果用户没有选中 记住我
  • Spring Security 页面无法在 Chrome 上的 Iframe 中打开

    我正在使用 Spring Boot Spring Security 和 jdk 1 8 当我尝试在 Chrome 上的 iframe 中打开任何安全的 Thymleaf 页面时 它每次都会将我重定向到登录页面 它在 Firefox 和 IE
  • 是否有一个 jQuery 选择器/方法来查找 n 级的特定父元素?

    考虑以下 HTML 如果我有对 元素的 JSON 引用 那么在这两种情况下如何获取对外部 元素的引用 table tr td td tr table
  • 使用 IIS 6 进行 Web 部署时出现问题

    我已经尝试使用 Visual Studio 2010 中的 Web 部署选项发布到安装了 Windows Server 2003 的 IIS 6 服务器很长时间了 我已在服务器上安装了 Web 部署代理 启动了服务并遵循此链接中的所有说明
  • 为什么 CSS 中的背景:url 不适用于 Django?

    我的导航栏有以下 CSS 代码 footer navigation background 1841c8 url images nav background gif height 40px padding 0 0 0 20px 但是 当我启动
  • 一个域上的 ProxyPass 和 DocumentRoot

    假设我有以下配置
  • 如何在 Objective-C (iPhone) 中连接字符串? [复制]

    这个问题在这里已经有答案了 可能的重复 如何在 Objective C 中连接字符串 https stackoverflow com questions 510269 how do i concatenate strings in obje
  • Pycharm:遇到调试点时如何专注于编辑器

    我使用的是mac Pycharm版本为2018 2 4社区版 当我使用调试器运行调试会话并命中调试点时 我必须使用鼠标单击编辑器才能在编辑器上键入代码 如果我不这样做并直接敲击键盘 Mac 会发出一些 bing 声 表明键盘输入对任何应用程
  • SignalR:连接建立时服务器如何正确订阅组

    我已经查看了几个地方 但仍然找不到关于如何使用组的明确说明 我正在使用组进行过滤 仅将消息传递给客户端子集 我想将客户端加入服务器端的组OnConnected事件 客户端不需要知道它属于哪个组 问题 我是否也应该覆盖OnReconnecte
  • Firebase google-services.json 文件

    我对 Firebase google services json 文件有疑问 每次我添加或更改某些内容时 例如 如果我添加新的 SHA1 指纹 是否需要再次下载该文件并将其放在 Android 项目的应用程序文件夹中 或者只使用第一次创建的
  • 更改 Firebase 电子邮件不会更新providerData

    我在我的 iOS 应用程序中使用 Firebase 用户使用 Firebase 的电子邮件和密码身份验证登录 目前 我正在创建允许用户更改电子邮件和密码的功能 我注意到使用成功更改电子邮件地址后changingEmailForUser 电子
  • CSS 边距为负而不移动父容器

    我正在尝试进入此页面 http musicaladvocacy org http musicaladvocacy org 显示 Home 灰色渐变中的白色容器 的区域向上移动约 60 px 但正如您所看到的 它同时将父容器向上移动 我只是想
  • 单选按钮上的 jQuery .change()

    我一定在这里遗漏了一些明显的东西 我无法理解 改变 http api jquery com change 触发单选按钮 我有下面的代码here http bjmarine net test html
  • CSS 图像精灵

    使用CSS图像精灵的唯一好处是减少http请求吗 或者还有其他好处吗 还有一种简单的方法可以确定要显示精灵的哪个区域的时间吗 正如您所说 主要优点之一是减少对服务器的请求数量 提高响应时间 特别是在加载大量小图像时 但这并不是人们使用精灵的
  • 计算 R 中数值向量的位数

    我在 R 中有一个数字向量 c 0 9 0 81 我想提取该向量中每个元素的位数 该命令将返回 在这种情况下 1 and 2因为数字是9 and 81 有方便的方法吗 另外 如果结果是1 如何扩展到两位数 例如 我希望返回的向量是 c 0
  • 坚持/提交在 Spring JPA JUnit 的测试环境中不起作用

    我正在尝试设置基本的 JPA 插入测试 但数据库中没有保存任何内容 数据库是Postgresql Hibernate 用作持久性提供者 提前谢谢了 Entity public class Currency Id GeneratedValue