springboot~基于单元测试的mongodb

2018-06-18 02:09:48来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

添加对应版本的包

testCompile('de.flapdoodle.embed:de.flapdoodle.embed.mongo:1.46.0')

在测试之前,它会根据你的操作系统去下载当前的mongodb,然后在宿主机上去跑它,可能第一次会比较慢 !

添加测试脚手架类

package com.example.springDemo;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import org.junit.After;
import org.junit.Before;


public class MongodbBaseTest {
    private static final MongodStarter starter = MongodStarter.getDefaultInstance();
    protected MongoClient mongo;
    protected DB db;
    private MongodExecutable mongodExecutable;
    private MongodProcess mongod;

    @Before
    public void setUp() throws Exception {
        mongodExecutable = starter.prepare(new MongodConfigBuilder()
                .version(Version.Main.PRODUCTION)
                .net(new Net(12345, Network.localhostIsIPv6())).build());
        mongod = mongodExecutable.start();


        mongo = new MongoClient("localhost", 12345);
        db = mongo.getDB("embedded-mongo");
    }

    @After
    public void tearDown() throws Exception {
        mongod.stop();
        mongodExecutable.stop();
    }
}

添加测试DEMO类

package com.example.springDemo;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
public class UserTest extends MongodbBaseTest {
    private DBCollection users;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        users = db.getCollection("users");
    }

    @Test
    public void should_insert_and_get_user() {
        final DBObject userDocument = new BasicDBObjectBuilder()
                .add("name", "lind")
                .get();
        users.insert(userDocument);

        final DBObject userDocumentFromDb = users.findOne(new BasicDBObject("_id", userDocument.get("_id")));

        assertThat(userDocumentFromDb.get("name"), is("lind"));
    }
}

测试如果通过,就出现pass 1的绿色标志

感谢各位阅读!

再次提醒,在测试之前,它会根据你的操作系统去下载当前的mongodb,然后在宿主机上去跑它,可能第一次会比较慢 !

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Hibernate-在Eclipse(Oxygen)中安装Hibernatetools插件

下一篇:关于ZK框架的onScroll事件的问题