JUnit Test Execution For a MongoDB Collection using Maven
Last Updated :
31 Aug, 2022
MongoDB is a NoSQL versatile database and it is widely used in software industries. Wherever there is no strict relational database relationship is necessary and also if there are chances of fetching the document often, it is always good to go with MongoDB. In this article, let us see the ways of
- Connecting to MongoDB,
- Creating collection,
- Inserting the document and test for the inserted data by JUnit
- Update the document and test for the updated data by JUNIT.
As a sample project, the whole operation is carried out. We can have this as a base project and it is getting done as a maven project.
Example Project
Project Structure:
Its a maven-driven project and hence let's start with
pom.xml
XML
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg.mongodbtesting</groupId>
<artifactId>mongodbTesting</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>mongodbTesting</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- mongodb dependency -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
<!-- junit dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
</project>
Let's see the important java file that does all the 4 steps as indicated above
JUnitTestingOfMongoDBCollection.java
In this file
- Connection establishment with MongoDB is done
- MongoDB is quite user-friendly. If there is no database exists, automatically it is created
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("localhost", 27017);
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("geeksforgeeks");
Similarly, if the collection does not exist, automatically it is created via the below code
/**** Get collection / table from 'geeksforgeeks' ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("authors");
By this point of time,
- 'geeksforgeeks' named database is created
- 'authors' named collection is created
Now let's insert the document and test for the same. After insertion, we can able to see "name", "age", "technology" and "createdDate" are the columns created and their respective values are tested. During updating the document, additionally, a new column called "numberofposts" is added and this kind of feasibility is possible easily in MongoDB. Let's test for the same. The whole set of code is given below.
Java
import java.util.Date;
// Following imports are necessary for JUNIT
import static org.junit.Assert.assertEquals;
import org.junit.Test;
// Following imports are necessary for MongoDB
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
public class JUnitTestingOfMongoDBCollection {
@Test
public void testInsertedAndUpdatedDocument() throws Exception {
try {
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("localhost", 27017);
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("geeksforgeeks");
/**** Get collection / table from 'geeksforgeeks' ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("authors");
/**** Insert ****/
// create a document to store key and value
BasicDBObject document = new BasicDBObject();
document.put("name", "author1");
document.put("age", 30);
document.put("technology", "java,mongodb");
document.put("createdDate", new Date());
table.insert(document);
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "author1");
DBCursor cursor = table.find(searchQuery);
// While displaying let us check
// with assert statements as well
while (cursor.hasNext()) {
DBObject object = cursor.next();
// Checking whether inserted name is author1
assertEquals("author1", object.get("name").toString());
// Checking whether inserted age is 30
assertEquals(30, Integer.parseInt(object.get("age").toString()));
// Checking whether inserted technology is java,mongodb
assertEquals("java,mongodb", object.get("technology").toString());
}
/**** Update ****/
// search document where name="author1"
// and update it with new values
BasicDBObject query = new BasicDBObject();
query.put("name", "author1");
BasicDBObject newDocument = new BasicDBObject();
// changing the technology column value
newDocument.put("technology", "java,.net,mongodb");
// additionally adding a new column.
// This is the advantage of mongodb.
// We no need to have concrete structure
// from the beginning as like RDBMS database
newDocument.put("numberofposts", "10");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
// This way we can update the document
table.update(query, updateObj);
/**** Find and display ****/
BasicDBObject searchQuery2
= new BasicDBObject().append("name", "author1");
DBCursor cursor2 = table.find(searchQuery2);
// Check the same as well
// Now we can check whether the technology
// got changed to java,.net,mongodb
// and also numberofposts to 10
while (cursor2.hasNext()) {
DBObject object = cursor2.next();
assertEquals("author1", object.get("name").toString());
assertEquals(30, Integer.parseInt(object.get("age").toString()));
assertEquals("java,.net,mongodb", object.get("technology").toString());
assertEquals("10", object.get("numberofposts").toString());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
We can execute the testing via below
Output:
After executing the whole program, let's compare the MongoDB data in the backend
Conclusion
MongoDB is a highly flexible versatile NoSQL database. We can easily connect MongoDB via java, insert and update the document as well as test the same via JUNIT by writing the code as given in the sample project.
Similar Reads
How to Delete a Document From MongoDB Collection using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. This means that MongoDB isnât based on a table-like relational database structure but provides an altogether different mechanism for data storage and retrieval. This stora
4 min read
How to Insert a Document into a MongoDB Collection using Node.js?
MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guid
5 min read
How to drop collection in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to create new Collection in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
1 min read
JUnit 5 â Conditional Test Execution
JUnit is one of the popular unit testing frameworks for Java projects. JUnit 5 is the latest version provided by the JUnit team launched with the aim of supporting the latest Java features and also providing notable advanced features to its predecessor JUnit 4. In this article, we will discuss one o
8 min read
How Many Documents are in a MongoDB Collection?
In MongoDB, data is organized into collections and documents. A collection is a grouping of documents similar to a table in a relational database but without a fixed schema it allowing for flexible data structures. Documents on the other hand are JSON-like structures composed of key-value pairs whic
6 min read
MongoDB Count() Method - db.Collection.count()
MongoDB's count() method is a powerful tool for retrieving the number of documents in a collection that match a specified query. It offers flexibility in filtering and is useful for obtaining quick counts based on various criteria.In this article, We will explain the MongoDB count() method in detail
5 min read
Maven Project - HashMap and HashSet Collections with JUnit Testing
In many software, we will be working with HashMap and HashSet and always there is confusion exists that when to use HashMap and when to use HashSet. As a sample project, a use case containing the "GeekAuthor" class is taken and it has different attributes namely authorNameauthorIdareaOfInterestpubl
7 min read
How to get information of all collections present in MongoDB database using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Inst
1 min read
Generate Junit Test Cases Using Randoop API in Java
Here we will be discussing how to generate Junit test cases using Randoop along with sample illustration and snapshots of the current instances. So basically in Development If we talk about test cases, then every developer has to write test cases manually. Which is counted in the development effort
4 min read