使用Spring Data Embedded Mongo在Mongo数据库中导入JSON文件 [英] Import JSON file in Mongo db using Spring Data Embedded Mongo

查看:176
本文介绍了使用Spring Data Embedded Mongo在Mongo数据库中导入JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些与需要从MongoDB中提取数据的方法有关的集成测试.详细地说,我正在使用 Flapdoodle 提供.

I am trying to write some integration tests relative to some methods that needs to extract data from MongoDB. In detail, I am using the Embedded Mongo given by Spring Data project. The embedded mongo is clearly provided by Flapdoodle.

我需要将一些json文件导入Embedded Mongo.我已经看过 flapdoodle 提供的测试,但是我无法理解它们如何与Spring Data + Spring Boot提供的 magic 集成.

I need to import some json file into the Embedded Mongo. I have looked at the tests provided with flapdoodle, but I am not able to understand how they integrates with the magic given by Spring Data + Spring Boot.

任何人都可以发布一些澄清的片段吗?

Can anyone post some clarifying snippets?

推荐答案

您可以创建一个junit规则(

You can create a junit rule (ExternalResource) which runs before and after each test. Check the MongoEmbeddedRule class to get some idea on the implementation details.

集成测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public abstract class TestRunner {

    @Autowired
    protected MongoTemplate mongoTemplate;

    @Rule
    public MongoEmbeddedRule mongoEmbeddedRule = new MongoEmbeddedRule(this);

外部资源规则:

public class MongoEmbeddedRule extends ExternalResource {

    private final Object testClassInstance;
    private final Map<String, Path> mongoCollectionDataPaths;
    private final String fieldName;
    private final String getterName;

    public MongoEmbeddedRule(final Object testClassInstance) {
        this(testClassInstance, "mongoTemplate", "getMongoTemplate");
    }

    protected MongoEmbeddedRule(final Object testClassInstance, final String fieldName, final String getterName) {
        this.fieldName = fieldName;
        this.getterName = getterName;
        this.testClassInstance = testClassInstance;
        this.mongoCollectionDataPaths = mongoExtendedJsonFilesLookup();
    }

    @Override
    protected void before() {
        dropCollections();
        createAndPopulateCollections();
    }

    @Override
    protected void after() {
    }

    protected Set<String> getMongoCollectionNames() {
        return mongoCollectionDataPaths.keySet();
    }

    public void dropCollections() {
        getMongoCollectionNames().forEach(collectionName -> getMongoTemplate().dropCollection(collectionName));
    }

    protected void createAndPopulateCollections() {
        mongoCollectionDataPaths.forEach((key, value) -> insertDocumentsFromMongoExtendedJsonFile(value, key));
    }

    protected MongoTemplate getMongoTemplate() {
        try {
            Object value = ReflectionTestUtils.getField(testClassInstance, fieldName);
            if (value instanceof MongoTemplate) {
                return (MongoTemplate) value;
            }
            value = ReflectionTestUtils.invokeGetterMethod(testClassInstance, getterName);
            if (value instanceof MongoTemplate) {
                return (MongoTemplate) value;
            }
        } catch (final IllegalArgumentException e) {
            // throw exception with dedicated message at the end
        }
        throw new IllegalArgumentException(
                String.format(
                        "%s expects either field '%s' or method '%s' in order to access the required MongoTemmplate",
                        this.getClass().getSimpleName(), fieldName, getterName));
    }

    private Map<String, Path> mongoExtendedJsonFilesLookup() {
        Map<String, Path> collections = new HashMap<>();
        try {
            Files.walk(Paths.get("src","test","resources","mongo"))
                    .filter(Files::isRegularFile)
                    .forEach(filePath -> collections.put(
                            filePath.getFileName().toString().replace(".json", ""),
                            filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return collections;
    }

    private void insertDocumentsFromMongoExtendedJsonFile(Path path, String collectionName) {
        try {
            List<Document> documents = new ArrayList<>();
            Files.readAllLines(path).forEach(l -> documents.add(Document.parse(l)));
            getMongoTemplate().getCollection(collectionName).insertMany(documents);
            System.out.println(documents.size() + " documents loaded for " + collectionName + " collection.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

带有 json文件(names.json) > MongoDB扩展JSON ,其中每个文档都在一行中,集合名称是不带扩展名的文件名.

json file (names.json) with MongoDB Extended JSON, where every document is in one line and the collection name is the filename without extension.

{ "_id" : ObjectId("594d324d5b49b78da8ce2f28"), "someId" : NumberLong(1), "name" : "Some Name 1", "lastModified" : ISODate("1970-01-01T00:00:00Z")}
{ "_id" : ObjectId("594d324d5b49b78da8ce2f29"), "someId" : NumberLong(2), "name" : "Some Name 2", "lastModified" : ISODate("1970-01-01T00:00:00Z")}

这篇关于使用Spring Data Embedded Mongo在Mongo数据库中导入JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆