简体   繁体   English

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

[英]Spring/MongoDB/Junit: Unit test with Fongo is giving the Null Pointer Exception

I am fairly new to unit testing and trying to test a simple function that returns a query. 对于单元测试和尝试测试一个返回查询的简单函数,我是一个新手。 In my unit test, I am getting the NullPointerException after calling the method. 在我的单元测试中,调用该方法后,我得到了NullPointerException I assume mongoOperations is null , and guessing that is the reason why it is returning NPE. 我假设mongoOperationsnull ,并且猜测这就是它返回NPE的原因。 I am using fongo to mock the mongoDB and I configured the spring context in testConfigurationContext.xml file. 我使用fongo模拟mongoDB,并在testConfigurationContext.xml文件中配置了spring上下文。

This is the class I want to test: 这是我要测试的课程:

@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);
    }
}

This is my unit test: 这是我的单元测试:

@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();
    }
}

This is the applicationContext file: 这是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>

This is the error on console: 这是控制台上的错误:

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)

I am guessing I am missing something. 我想我缺少了一些东西。 Any help would be greatly appreciated! 任何帮助将不胜感激!

I have never used Fongo, but usually I mock the mongo server with flapdoodle. 我从未使用过Fongo,但是通常我会用flappoodle模拟mongo服务器。 This is easy to implements. 这很容易实现。

I would like to recommend it. 我想推荐它。

https://github.com/flapdoodle-oss/de.flapdoodle.embed.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>

You are not auto-wiring DataVersionDaoMongo in you unit test, also mongoOperations bean either need to be auto-wired or injected via constructor. 您不是在单元测试中自动接线DataVersionDaoMongo ,也不需要mongoOperations bean自动接线或通过构造函数注入。

In you Repo class 在您的回购课程中

@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);
    }
}

and in your unit test, you no need to use new for bean creation. 在单元测试中,您无需使用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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM