Spring JUnit测试在我的服务类上保持返回nullpointerexception

时间:2012-11-23 10:45:51

标签: java spring testing junit

更新25-11-2012

嗨,好像我的上下文文件是错误的'classpath'他们必须在测试类路径中。我通过在src / test /文件夹中添加一个名为resources的文件夹来解决这个问题。在这里,我可以把我的应用程序上下文。我还从测试中删除了@TestExecutionListeners。我还需要为我的pom文件添加一些依赖项,用于javax / servlet / serlvetException等。如果有人有兴趣,可以在Github处查看我的代码,分支问题9。


问题[已解决]

我使用spring 3创建了一个简单的应用程序。我创建了一个服务类,它使用DAO类通过使用简单的JDBC模板将数据与数据库进行映射。

我的问题是当我试图对这些类进行集成测试时,它返回一个NullPointerException(参见Stacktrace)。这真的很烦人,因为我似乎无法找到答案,所以我希望你们能帮助我。下面我发布了所有不同的文件。

堆栈跟踪

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.115 sec <<< FAILURE!
test(dk.martinrohwedder.blog.test.ArticleServiceTest)  Time elapsed: 0.009 sec  <<< ERROR!
java.lang.NullPointerException
at dk.martinrohwedder.blog.service.ArticleService.getFiveLastArticles(ArticleService.java:30)
at dk.martinrohwedder.blog.test.ArticleServiceTest.test(ArticleServiceTest.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
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.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)

ArticleServiceTest

package dk.martinrohwedder.blog.test;

import dk.martinrohwedder.blog.domain.Article;
import dk.martinrohwedder.blog.service.ArticleService;
import java.util.ArrayList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
 *
 * @author Martin Rohwedder
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml"})
@TestExecutionListeners
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class ArticleServiceTest {

    @Autowired(required = true)
    private ArticleService articleService;

    //private EmbeddedDatabase db;

    @Before
    public void setUp() {
        //EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        //db = builder.setType(EmbeddedDatabaseType.HSQL).setName("blog").addScript("classpath:create-db.sql").addScript("classpath:test-data.sql").build();
        //articleService.getArticleDao().setDataSource(db);
        //articleService = new ArticleService();
    }

    @After
    public void tearDown() {
        //articleService.getArticleDao().setDataSource(null);
        //db.shutdown();
        //articleService = null;
    }

    @Test
    public void test()
    {
        ArrayList<Article> articles = articleService.getFiveLastArticles();

        int number = articles.size();
        assertEquals(3, number);
    }

}

ArticleService

package dk.martinrohwedder.blog.service;

import dk.martinrohwedder.blog.domain.Article;
import dk.martinrohwedder.blog.repository.ArticleDao;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 * @author Martin Rohwedder
 * @since 22-11-2012
 * @version 1.0
 */
@Service("articleService")
public class ArticleService {

    @Autowired(required = true)
    private ArticleDao articleDao;

    public ArticleDao getArticleDao() {
        return articleDao;
    }

    public void setArticleDao(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    public ArrayList<Article> getFiveLastArticles()
    {
        ArrayList<Article> articles = (ArrayList) articleDao.selectAllArticles();

        if (articles.size() > 5) {
            articles = (ArrayList) articles.subList(articles.size() - 6, articles.size());
        }

        return articles;
    }

}

ArticleDao

package dk.martinrohwedder.blog.repository;

import dk.martinrohwedder.blog.domain.Article;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
/**
 *
 * @author Martin Rohwedder
 * @since 22-11-2012
 * @version 1.0
 */
@Repository
public class ArticleDao implements IArticleDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired(required = true)
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public List<Article> selectAllArticles() {
        String sql = "select article_id, headline from article";
        return this.jdbcTemplate.query(sql, new ArticleMapper());
    }

    @Override
    public Article selectArticle(int articleId) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void insertArticle(Article article) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void updateArticle(Article article) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void deleteArticle(int articleId) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Article Mapper is responsible for map all rows found in a sql 
     * statement to Article objects.
     */
    private static final class ArticleMapper implements RowMapper<Article> {

        @Override
        public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
            Article article = new Article();
            article.setId(rs.getInt("article_id"));
            article.setHeadline(rs.getString("headline"));

            return article;
        }

    }

}

测试context.xml中

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

    <context:component-scan base-package="dk.martinrohwedder.blog" />

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="embeddedDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:blog"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <jdbc:embedded-database id="dataSource" type="HSQL"/>
        <jdbc:initialize-database data-source="embeddedDataSource">
        <jdbc:script location="classpath:create-db.sql"/>
        <jdbc:script location="classpath:test-data.sql"/>
    </jdbc:initialize-database>

</beans>

创建-db.sql

create database if not exists blog;

use blog;

drop table if exists article;

create table article
(
    article_id int unsigned not null auto_increment,
    headline varchar(30) not null,
    primary key (article_id)
);

测试data.xml中

insert into article (article_headline)
values ("Artikel 1");
insert into article (article_headline)
values ("Artikel 2");
insert into article (article_headline)
values ("Artikel 3");

test-context.xml,create-db.sql和test-data.sql都在类路径中,因为它们位于名为Other Sources(src / main / resources)的包中。

希望有人能帮助我。

2 个答案:

答案 0 :(得分:3)

尝试使用
  <context:annotation-config/>
而不是 <mvc:annotation-driven />
在test-context.xml文件中。

<mvc:annotation-driven/>是Spring 3.0中添加的标记,它执行以下操作:

  1. 配置Spring 3 Type ConversionService(替代 PropertyEditors)
  2. 添加了对使用@NumberFormat
  3. 格式化数字字段的支持
  4. 如果Joda Time在类路径上,则添加对使用@DateTimeFormat格式化Date,Calendar和Joda Time字段的支持
  5. 如果JSR-303提供程序在类路径上,则添加对使用@Valid验证@Controller输入的支持
  6. 如果JAXB在类路径上(使用@RequestBody / @ ResponseBody进行HTTP消息转换),则支持读取和写入XML支持
  7. 如果杰克逊在类路径上(与#5一样),则添加对JSON读写的支持。
  8. <context:annotation-config/>
    在定义的相同应用程序上下文中查找bean上的注释,并声明支持所有常规注释,如@ Autowired,@ Resource,@ Required,@ PostConstruct等。

答案 1 :(得分:1)

我认为articleDao没有被设置。如果要在测试中使用Spring bean,则无法在测试中实例化该服务。把这条线拿出来......

articleService = new ArticleService();