Spring单元测试java-config maven无法加载ApplicationContext

时间:2015-08-10 20:34:12

标签: java spring unit-testing applicationcontext

我试图用弹簧测试来测试我的应用程序,但经过大量的配置尝试后,我正在寻求帮助!

我的配置文件:

appConfig:

void calculate_normals() {
        for (int i = 0; i < d(); i+=4) {
            vec3 a = d[i];
            vec3 b = d[i+1];
            vec3 c = d[i+2];
            vec3 d = d[i+3];
            vec3 ba = b - a;
            vec3 ca = c - a;
            vec3 normal1;
            cross(&normal1, &ca, &ba);
            normal1.normalize();
            n.push_back(normal1);
            n.push_back(normal1);
            n.push_back(normal1);
            n.push_back(normal1);

            d[i].print();
            d[i+1].print();
            d[i+2].print();
            d[i+3].print();
            normal1.print();
            normal1.print();
            normal1.print();
            normal1.print();
            printf("\n");
}

PersistenceConfig.java

@Configuration
@Profile(value="profile1")
@ComponentScan(basePackages={"br.uem.gestaoresiduos"},
    excludeFilters=@ComponentScan.Filter(type=FilterType.REGEX, pattern={"br.uem.gestaoresiduos.web.*"}))
@PropertySource(value = { "classpath:application.properties" })
@EnableScheduling
@EnableAspectJAutoProxy
@EnableCaching
public class AppConfig{
    @Autowired
    private Environment env;

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public JavaMailSenderImpl javaMailSenderImpl() {
        JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
        mailSenderImpl.setHost(env.getProperty("smtp.host"));
        mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
        mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
        mailSenderImpl.setUsername(env.getProperty("smtp.username"));
        mailSenderImpl.setPassword(env.getProperty("smtp.password"));

        Properties javaMailProps = new Properties();
        javaMailProps.put("mail.smtp.auth", true);
        javaMailProps.put("mail.smtp.starttls.enable", true);

        mailSenderImpl.setJavaMailProperties(javaMailProps);

        return mailSenderImpl;
    }

    @Bean
    public CacheManager cacheManager()
    {
        return new ConcurrentMapCacheManager();
    }
}

}

pom.xml

@Configuration  
@EnableTransactionManagement
    @EnableJpaRepositories(basePackages="br.uem.gestaoresiduos.repositories")
@PropertySource(value = { "classpath:application.properties" })
public class PersistenceConfig 
{
@Autowired
private Environment env;

@Value("${init-db:false}")
private String initDatabase;

@Bean
public PlatformTransactionManager transactionManager()
{
    EntityManagerFactory factory = entityManagerFactory().getObject();
    return new JpaTransactionManager(factory);
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);

    factory.setDataSource(dataSource());
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("br.uem.gestaoresiduos.entities");

    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    factory.setJpaProperties(jpaProperties);

    factory.afterPropertiesSet();
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
    return factory;
}

@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator()
{
    return new HibernateExceptionTranslator();
}

@Bean
public DataSource dataSource()
{
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    return dataSource;
}

@Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) 
{
    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
    dataSourceInitializer.setDataSource(dataSource);
    ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
    databasePopulator.addScript(new ClassPathResource("db.sql"));
    dataSourceInitializer.setDatabasePopulator(databasePopulator);
    dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase));
    return dataSourceInitializer;
}   

User.java

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.uem</groupId>
<artifactId>tcc-gestao-residuos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<properties>
    <java.version>1.8</java.version>
    <junit.version>4.11</junit.version>
    <slf4j.version>1.7.5</slf4j.version>
    <logback.version>1.0.13</logback.version>
    <spring.version>4.2.0.RELEASE</spring.version>
    <spring-data-jpa.version>1.8.2.RELEASE</spring-data-jpa.version>
    <spring-security.version>3.2.0.RELEASE</spring-security.version>
    <hibernate.version>5.0.0.CR4</hibernate.version>
    <aspectj.version>1.7.2</aspectj.version>
    <mysql.version>5.1.26</mysql.version>
    <jackson-json.version>2.3.1</jackson-json.version>
    <commons-dbcp.version>1.2.2</commons-dbcp.version>
    <commons-lang3.version>3.1</commons-lang3.version>
    <my.tomcat.path>/root/workspace/tcc-gestao-residuos/target/tomcat</my.tomcat.path>
</properties>

<build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <webXml>\src\main\webapp\WEB-INF\web.xml</webXml>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <port>8080</port>
                <contextReloadable>true</contextReloadable>
                <outputDirectory>${my.tomcat.path}</outputDirectory>
            </configuration>

        </plugin>
    </plugins>
</build>

<dependencies>

    <!-- Logging dependencies -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
    </dependency>

    <!-- Spring dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
    </dependency>

    <!-- Spring Data JPA dependencies -->

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>${spring-data-jpa.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <!-- SpringSecurity dependencies -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>${spring-security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${spring-security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring-security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring-security.version}</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
    </dependency>

    <!-- Testing dependencies -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- DB dependencies -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>${commons-dbcp.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson-json.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.3</version>
    </dependency>

    <!-- Web dependencies -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>${spring.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

UserRepository.java

@Entity
@Table(name="users")
public class User 
{
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    @Column(nullable=false, unique=true)
    private String email;
    @Column(nullable=false)
    private String password;
    private Date dob;

    @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    @JoinColumn(name="user_id")
    private Set<Role> roles = new HashSet<>();
    ...  
}  

UserService.java

public interface UserRepository extends JpaRepository<User, Serializable>{
}

UserServiceTest.java

@Service
@Transactional
public class UserService 
{

@Autowired
private UserRepository userRepository;

public List<User> findAll() {
    return userRepository.findAll();
}

public User create(User user) {
    return userRepository.save(user);
}  

}

错误:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class UserServiceTest {

 @Configuration
 static class ContextConfiguration {

     @Bean
     public UserService userService() {
        UserService userService = new UserService();
        return userService;
    }
 }

@Autowired
private UserService userService;

private User user;

@Before
public void setUp() throws Exception {
    user = new User(1, "victor", "victort@asd.ad", "sfd", null);
}

@Test
public void testCreate() {
    User result = userService.create(user);
    user = result;
}

...

有人能帮助我吗?......这是正确的配置吗?缺什么?!?! 我在这里和其他网站上尝试了很多解决方案,但都失败了

对不起这个烂摊子......这是我的第一篇帖子

非常感谢

1 个答案:

答案 0 :(得分:0)

我认为您的项目中有web.xml个文件,该文件通过Spring springSecurityFilterChain引用DelegatingFilterProxy过滤器

您应该从web.xml中删除它以进行单元测试,或者将其添加到测试弹簧上下文