我想测试一个“服务”级别或“dao”级别的代码。
但我无法解决异常
“没有EntityManager绑定到此线程。尝试包装此调用 JPAApi.withTransaction,或确保设置HTTP上下文 这个帖子。“
这是我的junit测试代码。
以及在“createUser”函数中 userService.createUser(); 的代码是什么
@Inject
Application application;
@Before
public void setup() {
Module testModule = new AbstractModule() {
@Override
public void configure() {
}
};
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new ApplicationLoader.Context(Environment.simple()))
.overrides(testModule);
Guice.createInjector(builder.applicationModule()).injectMembers(this);
Helpers.start(application);
}
@After
public void teardown() {
Helpers.stop(application);
}
@Test
@Transactional
public void createUser() {
running(application, () -> {
UserService userService = application.injector().instanceOf(UserService.class);
userService.createUser();
});
}
请帮助我解决异常
thx~
答案 0 :(得分:0)
作为一个想法,您可以添加另一个注入的字段:
window.localStorage.setItem('displayName', data.google.displayName);
window.localStorage.setItem('photoUrl', data.google.photoURL);
然后在测试中,您可以拨打@Inject play.db.jpa.JPAApi japApi
答案 1 :(得分:0)
我找到了2.6.x版的解决方案,但也适用于2.5.x。
package models;
import org.junit.Before;
import org.junit.Test;
import play.Application;
import play.db.jpa.JPAApi;
import play.test.Helpers;
import play.test.WithApplication;
import java.util.stream.Stream;
import static org.junit.Assert.assertTrue;
public class MyRepositoryTest extends WithApplication {
@Override
public Application provideApplication() {
return Helpers.fakeApplication(Helpers.inMemoryDatabase());
}
JPAApi jpaApi;
MyRepository myRepository;
@Before
public void init() {
// must get instances like this, as application is created for each test
jpaApi = app.injector().instanceOf(JPAApi.class);
userRepository = app.injector().instanceOf(UserRepository.class);
// no need to setup / clear DB, WithApplication create new DB for each test
}
@Test
public void testGetAllEntries() {
// insert some data first
performNativeQuery("INSERT INTO ...");
// call tested method
final Stream<Entity> result = myRepository.getAllEntries();
// perform some assertions
assertTrue(result.count() == 1);
}
private void performNativeQuery(final String query) {
jpaApi.withTransaction(em -> em.createNativeQuery(query).executeUpdate());
}
}