Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JUnit Testing for Solr 6

DZone's Guide to

JUnit Testing for Solr 6

Want to test your Solr queries with JUnit? This guide will help you set up your dependencies and create and implement your tests.

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

Recently, I wanted to write some JUnit test cases to test Solr queries (these Solr queries were constructed in Solrj — a Java client library to access Solr), which I have written to retrieve data from the Solr index. When I was doing this, I could not find good documentation or tutorials and, therefore, I got to do a bit of trial and error to come up with the following model. I thought to write it down, hoping someone else may find it helpful.

My development environment was Gradle, and the following are the steps I used to set up the environment.

Setup

With the other entries relevant for your project, you the need following test environment in your build.gradle file.

testCompile (
    'junit:junit:4.12',
    'org.hamcrest:hamcrest-core:1.3',
    'org.apache.solr:solr-core:6.3.0',
)


The following image shows how to organize folders inside the project. Please see the folder “testdata” and its subfolders. This folder should be inside your project's “src/test/resources” folder. As you can see below, it shows the folder structures for two cores called “employee” and “department”. The “department” core should also have a similar folder structure as shown in the “employee” core.

Content of the core.property file:

collection.name=employee
name=employee
collection=employee
coreNodeName=core_node1

Content of the solr.xml file:

Here, in this file, you should have an entry for your main core.

<coreRootDirectory>employee</coreRootDirectory>


Please note the lib folder and JAR file inside it. Copy this JAR file from the “dist” folder of the Solr distribution folder.

Copy the index files created by Solr that you want to test to the data index folder (see the image above). Your test classes load and retrieve the data from those indexes.

Solrj and JUnit Test Cases

Now it's the time to write some Java code.

The following code snippets show the Solr query class for this. The query joins the “department” index to the “employee” index.

import org.apache.solr.client.solrj.SolrQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

publicclass EmployeeQuery {

       privatestaticfinal Logger LOGGER = LoggerFactory.getLogger(EmployeeQuery.class);
       privatefinal SolrQuery _query;
       public EmployeeQuery(){
               this._query = new SolrQuery();
               this._query.setQuery("{!join from=employee-id fromIndex=department to=id}{!v=$qq}");             
       }
      public EmployeeQuery setDepartmentId(String empId) {
              if (empId != null) {
                           this._query.add("qq", "id:"+ empId);
              }
              return this;
       }
   
       public SolrQuery toQuery() {
              LOGGER.debug("query {}", this._query.toQueryString());
              return  this._query;
       }


The following are the imports section of the test case:

import java.io.IOException;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.core.CoreContainer;
import org.junit.BeforeClass;
import org.junit.Test;
import org.testng.Assert;
import com.myorg.query.EmployeeQuery;


The following piece of code shows the implementation of the before class method of the test case. Inside that method, it loads the “employee” index for the test environment.

static EmbeddedSolrServer server;
static CoreContainer container;
static EmbeddedSolrServer contentServer;
      
 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
            
        container = new CoreContainer("src/test/resources/testdata/solr");
       container.load();
       server = new EmbeddedSolrServer( container, "employee" );
                            
       }

And finally, the following piece of code shows the implementation of the test method. As you can see, the “EmbeddedSolrServer” class is the key component for this test.

@Test
public void  testEmployee(){
             
       EmployeeQuery query = new EmployeeQuery();
       query.setEmployeeId("4788717");
       SolrQuery solrQuery = query.toQuery();
       QueryResponse qResp;
       try {
              qResp = server.query(solrQuery);
              SolrDocumentList docList = qResp.getResults();
              Assert.assertEquals(1, docList.size());
                    
              SolrDocument doc1 = docList.get(0);
              Assert.assertEquals("428666", doc1.getFieldValue("department-id"));
       } catch (SolrServerException | IOException e) {
                 e.printStackTrace();
       }
}


Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.

Topics:
junit ,solr ,java ,testing ,tutorial

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}