Tag: spring test

如何在Spring中的每次测试之前重新创建数据库?

我的Spring-Boot-Mvc-Web应用程序在application.properties文件中具有以下数据库配置: spring.datasource.url=jdbc:h2:tcp://localhost/~/pdk spring.datasource.username=sa spring.datasource.password= spring.datasource.driver-class-name=org.h2.Driver 这是我做的唯一配置。 我没有任何其他配置。 然而,Spring和子系统会在每个Web应用程序运行时自动重新创建数据库。 数据库在系统运行时重新创建,而在应用程序结束后包含数据。 我不理解这个默认值,并期望这适合测试。 但是当我开始运行测试时,我发现数据库只重建了一次。 由于测试是在没有预先定义的顺序下执行的,因此这是毫无意义的。 所以,问题是: 如何理解? 即如何在应用程序首次启动时在每次测试之前重新创建数据库? 我的测试类标题如下: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = myapp.class) //@WebAppConfiguration @WebIntegrationTest @DirtiesContext public class WebControllersTest { 如您所见,我在课堂级别尝试了@DirtiesContext但没有帮助。 UPDATE 我有一个豆子 @Service public class DatabaseService implements InitializingBean { 哪个有方法 @Override @Transactional() public void afterPropertiesSet() throws Exception { log.info(“Bootstrapping data…”); User user = createRootUser(); if(populateDemo) { populateDemos(); […]

如何在活跃的spring事务中将数据刷新到db?

我想使用spring测试框架测试hibernate session的save()方法。 @Test方法是: @Test @Transactional public void testSave() { User expected = createUser(); getGenericDao().currentSession().save(expected); User actual = getUser(generatedId); assertUsersEqual(expected,actual); } 我想将用户刷新到数据库中。 我想让我的用户在这个方法之后进入数据库 getGenericDao().currentSession().save(expected); 然后我想使用spring数据框架转到数据库,并通过下一行获取此保存的用户: User actual = getUser(generatedId); 我尝试使用hibernate flush方法,如: currentSession().setFlushMode(MANUAL); //do saving here currentSession().flush(); 它不会将我的用户刷新到数据库中! 但是,如果我没有使用@Transactional spring注释并将我的用户保存在程序化的spring事务中,那么我实现了我想要的。 不幸的是,由于没有spring @Transactional,因此保存到db的用户不会回滚。 因此,我的测试方法会更改后续测试方法的db和行为。 所以我需要将我的用户刷新到db里面的测试方法(不是在最后),并在测试方法结束时回滚所有对db的更改。 UPDATE建议准备方法如下: @Transactional public void doSave(User user){ getGenericDao().currentSession().save(user); } 并且在testSave中调用doSave什么都不做。 执行此方法后,我仍然没有db中的用户。 我设置断点并从命令行检查我的数据库。 更新非常感谢您的回复。 问题是方法flush()没有把我的用户放到database.I尝试Isolation.READ_UNCOMMITTED它并没有把我的用户放入数据库。 […]

Mockitoexception – when()需要一个必须是模拟方法调用的参数

我有一个非常简单的测试用例,它使用的是Mockito和Spring Test框架。 当我做 when(pcUserService.read(“1”)).thenReturn(pcUser); 我得到了这个例外。 org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be ‘a method call on a mock’. For example: when(mock.getArticles()).thenReturn(articles); Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods *cannot* be stubbed/verified. 2. inside when() you don’t call method on mock but on some other […]

如何在spring test中的@Test方法之前只填充一次数据库?

使用junit4测试spring服务层的下一个问题是:如何在所有@Test方法之前调用仅填充一次数据库的脚本:我想在所有@Tests之前执行一次: JdbcTestUtils.executeSqlScript(jdbcTemplate(), new FileSystemResource( “src/main/resources/sql/mysql/javahelp-insert.sql”), false); 我尝试在我的GenericServiceTest类上使用@PostConstruct(由测试类扩展)。 事实certificate,每次@Test方法之前都会调用@PostConstruct。 有趣的是,甚至在每个@Test方法之前调用注释了@Autowired of GenericServiceTest的方法。 我不希望在每个测试类之前填充数据库,但只在spring-test启动时填充一次。 如何在使用spring测试框架和junit4的所有@Test方法之前只执行一次上面的方法? 谢谢!

在测试方法中重新加载或刷新Spring应用程序上下文?

我需要在我的测试类的单个方法中更改我的applicationContext中活动的Spring配置文件,为此我需要在刷新竞赛之前运行一行代码,因为我使用的是ProfileResolver。 我尝试过以下方法: @WebAppConfiguration @ContextConfiguration(locations = {“/web/WEB-INF/spring.xml”}) @ActiveProfiles(resolver = BaseActiveProfilesResolverTest.class) public class ControllerTest extends AbstractTestNGSpringContextTests { @Test public void test() throws Exception { codeToSetActiveProfiles(…); ((ConfigurableApplicationContext)this.applicationContext).refresh(); … tests here … codeToSetActiveProfiles(… back to prior profiles …); … ideally refresh/reload the context for future tests } } 但我得到: java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call […]

使用profile进行Spring集成测试

在我们的Spring Web应用程序中,我们使用Spring bean配置文件来区分三种场景:开发,集成和生产。 我们使用它们连接到不同的数据库或设置其他常量。 使用Spring bean配置文件非常适合更改Web应用程序环境。 我们遇到的问题是我们的集成测试代码需要针对环境进行更改。 在这些情况下,集成测试会加载Web应用程序的应用程序上下文。 这样我们就不必重新定义数据库连接,常量等(应用DRY原则)。 我们设置了如下的集成测试。 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = [“classpath:applicationContext.xml”]) public class MyTestIT { @Autowired @Qualifier(“myRemoteURL”) // a value from the web-app’s applicationContext.xml private String remoteURL; … } 我可以使用@ActiveProfiles使其在本地运行,但这是硬编码的,导致我们的测试在构建服务器上失败。 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = [“classpath:applicationContext.xml”]) @ActiveProfiles(“development”) public class MyTestIT { … } 我也尝试使用@WebAppConfiguration希望它可能以某种方式从Maven导入spring.profiles.active属性,但这不起作用。 另外需要注意的是,我们还需要配置代码,以便开发人员可以运行Web应用程序,然后使用IntelliJ的测试运行器(或其他IDE)运行测试。 这对于调试集成测试来说要容易得多。

无法在ClassReader中加载由ArrayIndexOutOfBoundsException引起的ApplicationContext

当我运行junit测试类时,出现以下exception? 我怎么解决这个问题? Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) Caused by: java.lang.ArrayIndexOutOfBoundsException: 8 at org.springframework.asm.ClassReader.readUnsignedShort(Unknown Source) at org.springframework.asm.ClassReader.(Unknown Source) at org.springframework.asm.ClassReader.(Unknown Source) at org.springframework.asm.ClassReader.(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.(SimpleMetadataReader.java:48) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) […]

尝试使用Spring运行jUnit测试时出现NoSuchFieldError

到目前为止,我有两个测试。 一个只使用jUnit框架并且工作正常。 另一个使用spring-test库并在每次尝试运行时创建此exception。 什么可能导致问题的想法? 错误 java.lang.NoSuchFieldError: NULL at org.junit.runners.ParentRunner.(ParentRunner.java:48) at org.junit.runners.BlockJUnit4ClassRunner.(BlockJUnit4ClassRunner.java:59) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:104) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:27) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:32) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:41) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:31) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Maven测试依赖项 junit junit 4.7 test org.springframework spring-test ${org.springframework.version} test 依赖树 [INFO] [dependency:tree {execution: default-cli}] [INFO] […]

在春季测试中请求范围豆

我想在我的应用程序中使用请求范围的bean。 我使用JUnit4进行测试。 如果我尝试在这样的测试中创建一个: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { “classpath:spring/TestScopedBeans-context.xml” }) public class TestScopedBeans { protected final static Logger logger = Logger .getLogger(TestScopedBeans.class); @Resource private Object tObj; @Test public void testBean() { logger.debug(tObj); } @Test public void testBean2() { logger.debug(tObj); } 使用以下bean定义: 我得到: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘gov.nasa.arc.cx.sor.query.TestScopedBeans’: Injection of resource fields failed; nested exception […]