java 如何在Mongo中测试列表集合

0lvr5msh  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(88)

我有一个spring-boot项目,依赖于spring-data-mongo。一切都运行得很好。我有一个服务,它基本上在一个DB上执行listCollections,并清除该DB中所有集合的内容。
代码:

public void clearContentsOfAllCollections() {
    MongoDatabase db = this.mongoTemplate.getMongoDbFactory().getDb("any-db-name");
    LOGGER.info("=================================================================");
    LOGGER.info("Clearing collections in DB - {}", db.getName());
    MongoIterable<String> collectionNames = db.listCollectionNames();
    for (final String collectionName : collectionNames) {
      LOGGER.info("Clearing collection - {}", collectionName);
      db.getCollection(collectionName).deleteMany(new Document());
    }
    LOGGER.info("Successfully cleared DB - {}", db.getName());
    LOGGER.info("=================================================================");
  }

当我尝试编写单元测试时,这就是我所拥有的

@Test
  public void dropDBTest() {
    SimpleMongoClientDbFactory simpleMongoClientDbFactory = Mockito.mock(SimpleMongoClientDbFactory.class);
    MongoDatabase mongoDatabase = Mockito.mock(MongoDatabase.class);
    Mockito.when(mongoTemplate.getMongoDbFactory()).thenReturn(simpleMongoClientDbFactory);
    Mockito.when(simpleMongoClientDbFactory.getDb("db-name"))
      .thenReturn(mongoDatabase);

  // How do I convert this array list into a Mongo iterable 
     List<String> collectionList = Arrays.asList("collection-1", "collection-2");
  }

问题是--当我不得不模仿database.listCollectionNames()(从package com.mongodb.client)时,我不知道如何返回collectionList的内容。
另外,iterable.iterator()的类型是MongoCursor,我该如何测试它呢?我是不是漏掉了什么?

4jb9z9bj

4jb9z9bj1#

public class MongoDBTest {
            
         @Test
         public void testListCollectionNames() {
                // Set up the mock MongoDatabase
                MongoDatabase mockDatabase = Mockito.mock(MongoDatabase.class);
                // Set up the mock MongoIterable<String>
                MongoIterable<String> mockIterable = Mockito.mock(MongoIterable.class);
        
        
     Mockito.when(mockDatabase.listCollectionNames()).thenReturn(mockIterable);
             
        final var collectionNames = new ArrayList<>();
        collectionNames.add("testCollection")
        doReturn(collectionNames).when(mockIterable).into(new ArrayList<>());
                
            
                // Get the list of collection names
                List<String> collectionNames = mockDatabase.listCollectionNames().into(new ArrayList<>());
            
                // Assert that the test collection is in the list
                assertEquals(true, collectionNames.contains("testCollection"));
              }
            }

相关问题