Open In App

JUnit Test Execution For a MongoDB Collection using Maven

Improve
Improve
Like Article
Like
Save
Share
Report

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 

  1. Connecting to MongoDB,
  2. Creating collection,
  3. Inserting the document and test for the inserted data by JUnit
  4. 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:

Project Structure

 

Its a maven-driven project and hence let’s start with 

pom.xml

XML




         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:

JUnit Test Result

 

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.



Last Updated : 31 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads