如何在Springboot中使用Mockito模拟MongoDB连接以进行测试?

发布于 2025-02-02 08:14:21 字数 3159 浏览 5 评论 0原文

我是测试框架的新手 我必须测试一个涉及将数据中的数据存储到列表中的函数。

注意:我没有任何POJO类或实体课程。

我只是连接到数据库。以下是我想编写测试用例的方法。我对Junit和Mockito有基本知识。我知道如果我们有MongorePository或模板,那么我们可以使用@Mock注释,并可以模拟我们创建的回购。但是就我而言,我不知道该如何嘲笑DB。

以下是功能 -

public List<FriendDetails> fetchStationIds() {
        AtomicInteger count = new AtomicInteger();
        List<FriendDetails> list = new ArrayList<>();
        MongoDatabase database = mongoClient.getDatabase("Friends");
        MongoCollection<Document> collection = database.getCollection("Friend");
        BasicDBObject filter = new BasicDBObject("$and", Arrays.asList(new BasicDBObject("name", new BasicDBObject("$regex", "^Ram")).append("id", new BasicDBObject("$regex", "Shyam$"))));
        collection.find(filter).forEach((Consumer<Document>) doc -> {
            count.getAndIncrement();
            String name = (String) doc.get("name");
                if(name != null) {
                    String nameSpace = name.substring(0, name.indexOf("a") + 1);
                    String temp = name.substring(name.indexOf("a") + 1);
                    Document FriendValue1 = ((ArrayList<Document>) doc.get("Main_array")).get(0);
                    ArrayList<Document> arrayList = (ArrayList<Document>) FriendValue1.get("Main_ArrayPart2");
                    if(!arrayList.isEmpty()) {
                        Document FriendValue2 = arrayList.get(0);

                        Long number = (Long) FriendValue2.get("number");
                        String pinCode = (String) FriendValue2.get("pincode");
                        FriendDetails friendDetail = new FriendDetails(nameSpace, temp, number, pincode);
                        if (listDoesNotContain(list, friendDetail.toString())) {
                            list.add(friendDetail);
                        }
                    }
                }
        });
        return list;

    }

我尝试编写的测试用例 -

@Mock
    private MongoClient mockClient;
    @Mock
    private MongoCollection mockCollection;
    @Mock
    private MongoDatabase mockDB;

    @InjectMocks
    private FriendsDetails wrapper;

    @Before
    public void initMocks() {
        when(mockClient.getDatabase(anyString())).thenReturn(mockDB);
        when(mockDB.getCollection(anyString())).thenReturn(mockCollection);
        wrapper.initName();
        MockitoAnnotations.initMocks(this);
    }
   
        @Test
        void testFetch(){
      
            FindIterable iterable = mock(FindIterable.class); //which class I should mock
            MongoCursor cursor = mock(MongoCursor.class);
            Document bob = new Document("_id",new ObjectId("579397d20c2dd41b9a8a09eb"))
                    .append("firstName", "Bob")
                    .append("lastName", "Bobberson")
                     .append("number","36273872")
                     .append("pincode", "677");

            when(mockCollection.find()))
                    .thenReturn());

            assertEquals(expected, actual));
        }
    }

I'm new to testing framework
I have to test a function which have involves storing data from Db into list.

Note: I don't have any POJO Class or Entity class for this.

I'm just connecting to the database. Following is the method for which I want to write test cases. I have basic knowledge about Junit and Mockito. I know if we have MongoRepository or template then we can use the @Mock annotation and can mock the repo which we have created. But in my case I don't know how I should mock the DB.

Following is the function --

public List<FriendDetails> fetchStationIds() {
        AtomicInteger count = new AtomicInteger();
        List<FriendDetails> list = new ArrayList<>();
        MongoDatabase database = mongoClient.getDatabase("Friends");
        MongoCollection<Document> collection = database.getCollection("Friend");
        BasicDBObject filter = new BasicDBObject("$and", Arrays.asList(new BasicDBObject("name", new BasicDBObject("$regex", "^Ram")).append("id", new BasicDBObject("$regex", "Shyam
quot;))));
        collection.find(filter).forEach((Consumer<Document>) doc -> {
            count.getAndIncrement();
            String name = (String) doc.get("name");
                if(name != null) {
                    String nameSpace = name.substring(0, name.indexOf("a") + 1);
                    String temp = name.substring(name.indexOf("a") + 1);
                    Document FriendValue1 = ((ArrayList<Document>) doc.get("Main_array")).get(0);
                    ArrayList<Document> arrayList = (ArrayList<Document>) FriendValue1.get("Main_ArrayPart2");
                    if(!arrayList.isEmpty()) {
                        Document FriendValue2 = arrayList.get(0);

                        Long number = (Long) FriendValue2.get("number");
                        String pinCode = (String) FriendValue2.get("pincode");
                        FriendDetails friendDetail = new FriendDetails(nameSpace, temp, number, pincode);
                        if (listDoesNotContain(list, friendDetail.toString())) {
                            list.add(friendDetail);
                        }
                    }
                }
        });
        return list;

    }

Test case I tried to write --

@Mock
    private MongoClient mockClient;
    @Mock
    private MongoCollection mockCollection;
    @Mock
    private MongoDatabase mockDB;

    @InjectMocks
    private FriendsDetails wrapper;

    @Before
    public void initMocks() {
        when(mockClient.getDatabase(anyString())).thenReturn(mockDB);
        when(mockDB.getCollection(anyString())).thenReturn(mockCollection);
        wrapper.initName();
        MockitoAnnotations.initMocks(this);
    }
   
        @Test
        void testFetch(){
      
            FindIterable iterable = mock(FindIterable.class); //which class I should mock
            MongoCursor cursor = mock(MongoCursor.class);
            Document bob = new Document("_id",new ObjectId("579397d20c2dd41b9a8a09eb"))
                    .append("firstName", "Bob")
                    .append("lastName", "Bobberson")
                     .append("number","36273872")
                     .append("pincode", "677");

            when(mockCollection.find()))
                    .thenReturn());

            assertEquals(expected, actual));
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文