标签: spring-test

使用H2 db配置进行Spring测试

我在生产环境中使用Oracle,我想使用H2进行测试.我可以打字;

<jdbc:embedded-database id="dataSource">
  <jdbc:script location="classpath:schema.sql"/>
  <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
Run Code Online (Sandbox Code Playgroud)

所以我的表和脚本是自动创建的.但是我无法设置此db的URL值.(对于H2-Oracle兼容性,我应该添加; MODE = Oracle到url部分)

有没有办法实现这个目标?

或者只是相反的解决方案;

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:file:h2\db"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>        
</bean>
Run Code Online (Sandbox Code Playgroud)

在这个时候,我可以编辑URL部分,但是如何将默认测试脚本(创建和数据sqls)加载到此数据源?

h2 spring-test

16
推荐指数
2
解决办法
3万
查看次数

Ehcache关闭在运行测试套件时导致异常

我遇到了以下问题.

我的项目中有一套测试服,每个测试都运行良好.

但是,当我将它们作为套件运行时,我们中的一些会因以下异常而失败:

Caused by: java.lang.IllegalStateException: The dao Cache is not alive (STATUS_SHUTDOWN)
    at net.sf.ehcache.Cache$CacheStatus.checkAlive(Cache.java:4269)
    at net.sf.ehcache.Cache.checkStatus(Cache.java:2703)
    at net.sf.ehcache.Cache.get(Cache.java:1576)
    at org.springframework.cache.ehcache.EhCacheCache.get(EhCacheCache.java:61)
    at org.springframework.cache.interceptor.CacheAspectSupport.inspectCacheables(CacheAspectSupport.java:310)
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:198)
    at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
Run Code Online (Sandbox Code Playgroud)

有没有办法避免这种行为,即在多次测试中保持缓存活着还是正确关闭?

spring ehcache spring-test junit4

16
推荐指数
1
解决办法
1万
查看次数

如何在@ Configuration/@ Bean使用的单元测试中禁用Spring自动装配

我想使用spring-test配置内部类(@Configuration)配置组件测试.经过测试的组件有一些我想模拟测试的服务.这些服务是类(没有使用接口)并且@Autowired在其中具有spring注释().Mockito可以很容易地模仿它们,但是,我发现无法禁用弹簧自动装配.

我可以轻松重现的示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SomeTest.Beans.class)
public class SomeTest {

    // configured in component-config.xml, using ThirdPartyService
    @Autowired
    private TestedBean entryPoint;

    @Test
    public void test() {
    }

    @Configuration
    @ImportResource("/spring/component-config.xml")
    static class Beans {
        @Bean
        ThirdPartyService createThirdPartyService() {
            return mock(ThirdPartyService.class);
        }
    }
}

public class ThirdPartyService {
    @Autowired
    Foo bar;
}

public class TestedBean {
    @Autowired
    private ThirdPartyService service;
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,"TestBean"表示要模拟的服务.我不希望春天注入"酒吧"!@Bean(autowire = NO)没有帮助(事实上,这是默认值).(请保存我从"使用界面!"评论 - 模拟服务可以是第三方,我无法做任何事情.)

UPDATE

Springockito部分解决了这个问题,只要你没有其他任何东西可以配置(所以你不能使用Springockito的配置类 - 它不支持它),但只使用模拟.还在寻找纯弹簧解决方案,如果有的话...

java junit spring spring-test mockito

16
推荐指数
3
解决办法
1万
查看次数

无法处理上下文配置的位置和类

我写过以下测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:META-INF/dataContext.xml"},classes = Configiuration.class)
@ActiveProfiles("test")
public class CityDaoImplTest {
....
}
Run Code Online (Sandbox Code Playgroud)

我需要在调用时使用xml文件和java类bur中的配置

mvn test我在控制台中看到以下内容:

Tests in error: 
  initializationError(***.CityDaoImplTest): Cannot process locations AND classes for context configuration [ContextConfigurationAttributes@5bb21b69 declaringClass = '***.CityDaoImplTest', classes = '{***.Configiuration}', locations = '{classpath:META-INF/dataContext.xml}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader']; configure one or the other, but not both.
Run Code Online (Sandbox Code Playgroud)

如何在不重写配置的情况下修复它?

java testing configuration junit spring-test

16
推荐指数
2
解决办法
1万
查看次数

Maven:NoClassDefFoundError:org.springframework.test.context.junit4.SpringJUnit4ClassRunner

我有一个类路径问题.

  • 背景:构建和运行Spring WebApp.
  • 最初它是一个大项目,包括dao/service/controller/webapp.
  • 我刚刚将我的项目分解为maven模块项目,主要是从dao和服务层拆分webapp.
  • 现在我的webapp junit测试没有运行.
  • junit代码没有改变,我认为依赖关系没有改变(尽管转移了).
  • Spring-test在我的本地存储库中.
  • Spring-test在我的单元测试运行时类路径中(使用mvn debug logging来检查)
  • 我没有其他类路径问题.所有dao模块测试运行正常

但是,我明白了

java.lang.NoClassDefFoundError: Could not initialize class
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.
Run Code Online (Sandbox Code Playgroud)

我将发布我的父母和孩子pom.xml.如果有人有任何建议,我将非常感激.

父Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>jake</groupId>


    <artifactId>prototype3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>


    <modules>
        <module>prototype3.model</module>
        <module>prototype3.service</module>
        <module>prototype3.testadmin.webapp</module>
    </modules>

    <properties>
        <spring.version>4.1.6.RELEASE</spring.version>
        <thymeleaf.version>2.1.4.RELEASE</thymeleaf.version>
        <webflow.version>2.4.0.RELEASE</webflow.version>
        <internalrepo.dir>C:\Users\jake\_servers\internalRepository</internalrepo.dir>
    </properties>


    <distributionManagement>
        <repository>
            <id>internal.repo</id>
            <name>Temporary Staging Repository</name>
            <url>file://${internalrepo.dir}</url>
        </repository>
    </distributionManagement>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
            </dependency>


            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId> …
Run Code Online (Sandbox Code Playgroud)

spring-test maven

16
推荐指数
3
解决办法
3万
查看次数

春季启动.@DataJpaTest H2嵌入式数据库创建模式

我的数据层中有几个实体存储在特定模式中.例如:

@Entity
@Table(name = "FOO", schema = "DUMMY")
public class Foo {}
Run Code Online (Sandbox Code Playgroud)

我正在尝试设置H2嵌入式数据库,以便对我的数据层进行集成测试.我正在@DataJpaTest为我的测试使用注释来自动配置H2嵌入式数据库.但是,表的创建失败,因为DUMMY在初始化时不会创建模式.

有关如何在测试用例中创建表之前创建模式的任何想法?

我试过使用@Sql(statements ="CREATE SCHEMA IF NOT NOT DISMY")但没有成功.

此外,我试图spring.datasource.url = jdbc:h2:mem:test;INIT=CREATE SCHEMA IF NOT EXISTS DUMMY在我的test.properties文件中设置TestPropertySource("classpath:test.properties"),但这也不起作用.

integration-testing h2 spring-test embedded-database spring-boot

16
推荐指数
2
解决办法
1万
查看次数

无法使用Spring进行JUnit测试

我的测试定义如下:

package com.mytest;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringTestCase { 

    @Test
    public void testSave_success() {
        fail("Not implemented");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的意图是运行此测试并失败!

我的测试的spring配置文件位于:

 /com/mytest/SpringTestCase-context.xml
Run Code Online (Sandbox Code Playgroud)

我的spring配置文件的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

</beans>
Run Code Online (Sandbox Code Playgroud)

当我运行我的测试时,我得到以下异常:

java.lang.NoClassDefFoundError: org/springframework/core/AttributeAccessorSupport
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:117)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:119)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:108)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at …
Run Code Online (Sandbox Code Playgroud)

java spring spring-test junit4

15
推荐指数
1
解决办法
3万
查看次数

如何在活跃的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);
}
Run Code Online (Sandbox Code Playgroud)

我想将用户刷新到数据库中.我想让我的用户在这个方法之后进入数据库

getGenericDao().currentSession().save(expected);
Run Code Online (Sandbox Code Playgroud)

然后我想使用spring数据框架转到数据库,并通过下一行获取此保存的用户:

User actual = getUser(generatedId);
Run Code Online (Sandbox Code Playgroud)

我尝试使用hibernate flush方法,如:

currentSession().setFlushMode(MANUAL);
//do saving here
currentSession().flush();
Run Code Online (Sandbox Code Playgroud)

它不会将我的用户刷新到数据库中!但是,如果我没有使用@Transactional spring注释并将我的用户保存在编程弹簧事务中,那么我实现了我想要的.不幸的是,由于没有spring @Transactional,因此保存到db的用户不会回滚.因此,我的测试方法会更改后续测试方法的db和行为.

所以我需要将我的用户刷新到db里面的测试方法(不是在最后),并在测试方法结束时回滚所有对db的更改.

UPDATE建议准备方法如下:

@Transactional
public void doSave(User user){
    getGenericDao().currentSession().save(user);
}
Run Code Online (Sandbox Code Playgroud)

并且在testSave中调用doSave什么都不做.执行此方法后,我仍然没有db中的用户.我设置断点并从命令行检查我的数据库.

更新非常感谢您的回复.问题是方法flush()不会将我的用户放入数据库.我尝试了Isolation.READ_UNCOMMITTED并且它没有将我的用户放入数据库.我可以实现我想要的,但前提是我在@Test方法上关闭spring事务并在程序化事务中保存.然后@Test方法不回滚,为后续的@Test方法留下保存的用户.这里保存用户的@Test方法不像删除用户的@Test方法那样危险,因为它没有回滚.因此必须对@Test方法提供Spring事务支持,我无法将我的用户(或删除)放入db.实际上,只有在@Test方法结束并且@Test方法的事务被调用后,才会将用户放入(或删除)到db中.所以我想在@Test方法的中间将我的用户保存到db中,并在@Test方法结束时回滚它

谢谢!

java hibernate spring-test hibernate-session spring-transactions

15
推荐指数
3
解决办法
3万
查看次数

使用Servlet 2.5测试Spring Framework 4

我在使用Servlet 2.5让Spring Framework 4与我现有的项目一起工作时遇到了问题.我的web项目实际上运行正常,但我的测试用例失败并且它是由引起MockHttpServletRequest此异常引起的: -

java.lang.NoClassDefFoundError: javax/servlet/AsyncContext
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
Run Code Online (Sandbox Code Playgroud)

我尝试添加任一依赖项,但我会得到其他与Servlet 3.0相关的异常: -

<dependency>
 <groupId>javax</groupId>
 <artifactId>javaee-api</artifactId>
 <version>6.0</version>
 <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>servlet-api</artifactId>
  <version>3.0.20090124</version>
  <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

基于Spring Framework网站,它可以与Servlet 2.5一起使用.但是,Spring 4MockHttpServletRequest似乎依赖于Servlet 3.0.

我该如何解决这个问题?谢谢.

java spring spring-test

15
推荐指数
1
解决办法
8063
查看次数

如何在SpringJunit4TestRunner中将@ComponentScan与特定于测试的ContextConfiguration一起使用?

我正在测试一个Spring Boot应用程序.我有几个测试类,每个测试类都需要一组不同的模拟或其他定制的bean.

这是设置草图:

的src/main/java的:

package com.example.myapp;

@SpringBootApplication
@ComponentScan(
        basePackageClasses = {
                MyApplication.class,
                ImportantConfigurationFromSomeLibrary.class,
                ImportantConfigurationFromAnotherLibrary.class})
@EnableFeignClients
@EnableHystrix
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

package com.example.myapp.feature1;

@Component
public class Component1 {
    @Autowired
    ServiceClient serviceClient;

    @Autowired
    SpringDataJpaRepository dbRepository;

    @Autowired
    ThingFromSomeLibrary importantThingIDontWantToExplicitlyConstructInTests;

    // methods I want to test...
}
Run Code Online (Sandbox Code Playgroud)

的src /测试/ JAVA:

package com.example.myapp;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@ActiveProfiles("test")
public class Component1TestWithFakeCommunication {

    @Autowired
    Component1 component1; // <-- the thing we're testing. wants the above …
Run Code Online (Sandbox Code Playgroud)

spring spring-test spring-boot

15
推荐指数
3
解决办法
3万
查看次数