Spring / MongoDB / Junit:Fongo进行的单元测试给出了Null指针异常

时间:2018-11-03 23:48:06

标签: spring spring-mvc junit nullpointerexception fongo

对于单元测试和尝试测试一个返回查询的简单函数,我还很陌生。在单元测试中,调用该方法后得到NullPointerException。我假设mongoOperationsnull,并且猜测这就是它返回NPE的原因。我正在使用fongo模拟mongoDB,并在testConfigurationContext.xml文件中配置了spring上下文。

这是我要测试的课程:

@Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {

public DataVersionDaoMongo() {
    initType();
}

@Override
public DataVersion 

findByDBAndCollection(String dbName, String collectionName) {
//below is the line 27 on error console
return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
    }
}

这是我的单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
    private DataVersionDaoMongo dataVersionDaoMongo = new DataVersionDaoMongo();
    private MongoOperations mongoOperations;
    private DataVersion dataVersion;

    @Rule
    public FongoRule fongoRule = new FongoRule();

    @Test
    public void findByDBAndCollection() {
        String dbname = "mydb";
        String collectionName = "mycollection";
        DB db = fongoRule.getDB(dbname);
        DBCollection collection = db.getCollection(collectionName);
        Mongo mongo = fongoRule.getMongo();
        collection.insert(new BasicDBObject("name", "randomName"));
//below is the line 63 on error console
        assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
    }
}

这是applicationContext文件:

<?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:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">


    <bean name="fongo" class="com.github.fakemongo.Fongo">
        <constructor-arg value="InMemoryMongo" />
    </bean>
    <bean id="mongo" factory-bean="fongo" factory-method="getMongo" />

    <mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />

    <!-- localhost settings for mongo -->
    <!--<mongo:db-factory id="mongoDbFactory" />-->

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory"/>
    </bean>

</beans>

这是控制台上的错误:

java.lang.NullPointerException
    at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongo.findByDBAndCollection(DataVersionDaoMongo.java:27)
    at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongoTest.findByDBAndCollection(DataVersionDaoMongoTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

我猜我正在丢失一些东西。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

我从没使用过Fongo,但是通常我会用flappoodle模拟mongo服务器。这很容易实现。

我想推荐它。

https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo

<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <version>2.1.1</version>
    <scope>test</scope>
</dependency>

答案 1 :(得分:0)

在单元测试中,您不会自动装配DataVersionDaoMongomongoOperations bean也需要自动装配或通过构造函数注入。

在您的回购课程中

@Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {

    @Autowire MongoOperations mongoOperations;

    public DataVersionDaoMongo() {
        initType();
    }

    @Override
    public DataVersion findByDBAndCollection(String dbName, String collectionName) {
        //below is the line 27 on error console
        return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
    }
}

并且在单元测试中,无需使用new来创建bean。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
    @Autowire
    private DataVersionDaoMongo dataVersionDaoMongo;
    @Autowire
    private MongoOperations mongoOperations; // you can remove this, if not using it
    private DataVersion dataVersion;

    @Rule
    public FongoRule fongoRule = new FongoRule();

    @Test
    public void findByDBAndCollection() {
        String dbname = "mydb";
        String collectionName = "mycollection";
        DB db = fongoRule.getDB(dbname);
        DBCollection collection = db.getCollection(collectionName);
        Mongo mongo = fongoRule.getMongo();
        collection.insert(new BasicDBObject("name", "randomName"));
        //below is the line 63 on error console
        assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
    }
}