Mongodb集成测试。未创建测试数据

时间:2016-08-11 11:20:08

标签: java mongodb unit-testing embed

我正在尝试使用嵌入式mongodb测试我的mongodb dao,但是没有创建测试数据。

相比之下,如果我使用相同的方法在真实数据库中创建对象,那么它可以正常工作。

这是我的配置:

public class UnmappableDataDAOTest
{
    private static final String LOCALHOST = "127.0.0.1";
    private static final String DB_NAME = "itest";
    private static final int MONGO_TEST_PORT = 27028;
    private static final String CONTRACT_COLLECTION = "ContractAnswers";

    private UnmappableDataDAO dao;

    private static MongodProcess mongoProcess;
    private static Mongo mongo;

    private MongoTemplate template;


    @BeforeClass
    public static void initializeDB() throws IOException
    {
        RuntimeConfig config = new RuntimeConfig();
        config.setExecutableNaming(new UserTempNaming());

        MongodStarter starter = MongodStarter.getInstance(config);

        MongodExecutable mongoExecutable = starter.prepare(new MongodConfig(Version.V2_2_0, MONGO_TEST_PORT, false));
        mongoProcess = mongoExecutable.start();

        mongo = new Mongo(LOCALHOST, MONGO_TEST_PORT);
        mongo.getDB(DB_NAME);
    }

    @AfterClass
    public static void shutdownDB() throws InterruptedException {
        mongo.close();
        mongoProcess.stop();
    }

    @Before
    public void setUp() throws Exception {
        dao = new UnmappableDataDAO();
        template = new MongoTemplate(mongo, DB_NAME);
        dao.setMongoOperations(template);
    }

    @After
    public void tearDown() throws Exception
    {
        template.dropCollection(ContractAnswers.class);
    }

    @Test
    public void testCreate()
    {
        // Setup Test Data
        List<ContractAnswers> contractAnswersList = new ArrayList<>();

        ContractAnswers first = new ContractAnswers();
        first.setContractId(1L);
        first.setTemplateName("firstTemplate");
        first.setId("1");
        contractAnswersList.add(first);

        ContractAnswers second = new ContractAnswers();
        second.setContractId(2L);
        second.setTemplateName("secondTemplate");
        second.setId("2");
        contractAnswersList.add(second);

        for (ContractAnswers contractAnswers : contractAnswersList)
        {
            template.save(contractAnswers, CONTRACT_COLLECTION);
        }

        ContractAnswers third = new ContractAnswers();
        third.setContractId(3L);
        third.setTemplateName("thirdTemplate");
        third.setId("3");
        dao.create(third);

        List<ContractAnswers> list = template.findAll(ContractAnswers.class);
     }
}

findAll()方法的结果为null。这意味着,尚未创建该数据。

当我使用这种创建方式:template.save(contractAnswers, CONTRACT_COLLECTION);时,测试数据创建的,但我需要使用CONTRACT_COLLECTION作为参数。我的所有方法都依赖于它。

这很奇怪,但这就是我的创建方法看起来的样子并且工作正常:

public void createOrUpdate(ContractAnswers contractAnswers)
    {
        this.mongoOperations.save(contractAnswers, CONTRACT_COLLECTION);
    }

相同的代码在真实数据库中可以正常工作,但在测试中不起作用。

谢谢。

0 个答案:

没有答案
相关问题