简体   繁体   English

在测试框架中使用Hibernate的Java Play Framework 2.0

[英]Java Play Framework 2.0 using Hibernate in test framework

I'm wondering if anyone has got automated tests working with Play 2.0 using Hibernate as the persistance engine? 我想知道是否有人使用Hibernate作为持久性引擎对Play 2.0进行了自动化测试?

I'm attempting the following test but I get this errror: 我正在尝试以下测试,但出现此错误:

[error] Test tests.TestApp.findById failed: No EntityManager bound to this threa
d. Try to annotate your action method with @play.db.jpa.Transactional
[error]     at play.db.jpa.JPA.em(JPA.java:45)
[error]     at models.User.findById(User.java:72)
[error]     at tests.TestApp$1.run(TestApp.java:55)
[error]     at play.test.Helpers.running(Helpers.java:277)
[error]     at tests.TestApp.findById(TestApp.java:51)

The test code is: 测试代码为:

@Test
public void findById() 
{
    running(fakeApplication(), new Runnable() 
    {
       public void run() 
       {
           User user = User.findById(21l);
           assertThat(user.getName()).isEqualTo("Dave");
       }
    });
}

I tried adding the @Transactional anotation to the test method but this has no effect. 我尝试将@Transactional批注添加到测试方法,但这无效。

Then I tried adding setup and teardown methods that bind to the current JPA thread but had no luck with this either. 然后,我尝试添加绑定到当前JPA线程的设置和拆卸方法,但也没有运气。 Although I am not sure if I am doing it correctly. 尽管我不确定自己是否做得正确。

private EntityManager em;


@Transactional
@Before
public void setUp() 
{
    em = JPA.em("org.hibernate.ejb.HibernatePersistence");
    JPA.bindForCurrentThread(em);
}

@After
public void tearDown() 
{
    JPA.bindForCurrentThread(null);
    em.close();
}

This gives the following error: 这给出了以下错误:

[error] Test tests.TestApp.findById failed: There is no started application
[error]     at scala.sys.package$.error(package.scala:27)
[error]     at play.api.Play$$anonfun$current$1.apply(Play.scala:44)
[error]     at play.api.Play$$anonfun$current$1.apply(Play.scala:44)
[error]     at scala.Option.getOrElse(Option.scala:108)
[error]     at play.api.Play$.current(Play.scala:44)
[error]     at play.api.Play.current(Play.scala)
[error]     at play.Play.application(Play.java:12)
[error]     at play.db.jpa.JPA.em(JPA.java:21)
[error]     at tests.TestApp.setUp(TestApp.java:26)
[error]     ...

If anybody can provide any assistance I will appreciate it greatly! 如果有人可以提供任何帮助,我将不胜感激!

Try this pattern: 试试这个模式:

running(fakeApplication(), new Runnable()
{
  public void run()
  {
    JPA.withTransaction(new play.libs.F.Callback0()
    {
      public void invoke() throws DataAccessException
      {
        ...
      }
    });
  }
});

Here 's another example which shows the logic in setup and teardown methods as you have tried with bindForCurrentThread, in an abstract base class. 是另一个示例,它显示了在抽象基类中使用bindForCurrentThread尝试过的设置和拆卸方法中的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM