最终的一致性和测试用例

时间:2011-11-22 07:22:05

标签: mongodb unit-testing nosql

在处理MongoDB等最终一致的数据存储时编写测试用例的最佳实践是什么?

我当前的设置是Mongodb,其中3节点主/从/从设置,slave-ok设置为true。这意味着主节点用于只写,而两个从节点用于只读。

数据在从站上保持一致所用的时间相对较短,并且取决于操作和数据大小。例如,删除操作约3毫秒,1000个对象批量插入约200毫秒。

我的目标是测试我的Dao上的操作。它们可能很简单,如getById,delete,insert或findByExample等复杂的。我需要验证它们是否正常工作,最终在一些超时限制内是否可以接受。

这是我当前测试删除操作的内容,例如:

  @Test
  public void deleteTest() throws InstantiationException,
              IllegalAccessException {
        MyObject obj = new MyObject();
        obj.setName("test object");
        obj.save(obj);
        MyObject found = dao.findById(obj.getId());
        logger.info ("before: " + found);
        Assert.assertEquals(obj, found);

        dao.delete(obj.getId());
        MyObject deleted = null;
        long start = System.nanoTime();
        do {
              //TBD: need to add escape condition/timeout, else may be infinite loop....
              deleted = dao.findById(obj.getId());
              logger.info ("While: " + deleted);
        } while (deleted!=null);
        logger.info("It took " + ((System.nanoTime()-start)/1000000.00) + " ms for delete to be consistent");
        Assert.assertEquals(null, d1);
  } 

2 个答案:

答案 0 :(得分:1)

想到了几个想法

  1. 在制作中,如果你准备好从奴隶,你永远不会知道你是否获得了最新的数据。这是MongoDB中读取从属的权衡。我的经验是,在正常的工作条件下,奴隶是最新的。如果您必须获取最新数据,请查询主数据。
  2. 我肯定会开始使用mms来跟踪您的副本延迟。这将告诉您奴隶的落后程度,以便您可以了解数据的可用速度。
  3. 至于原始测试问题,这取决于您的目标。无论是副本还是独立的DAO都应该能够读取和写入相同的内容。您只需要确保您的应用程序了解它查询的数据可能不是最新的数据。

答案 1 :(得分:1)

对于你正在做的事情,你可以依赖这样一个事实,即使用副本集,mongo将始终写入主服务器。所以我会将删除测试更改为:

/*
 * get this from the DAO,
 * or use the instance injected into the DAO, etc.
 */
DBCollection collection = something();
DBCursor itemsRemaining = collection.find(); //find everything
itemsRemaining.setReadPreference(ReadPreference.PRIMARY); //force query to the master
Assert.assertEquals(0, itemsRemaining.count());

直接通过DBCollection进行测试可以强制测试查询使用master。我会测试findById(anyOldId)在单独测试中该项不在集合中时将返回null。

相关问题