I\'m coding some tests for my solr-indexer application. Following testing best practices, I want to write code self-dependant, just loading the schema.xml
and
You can start with the SolrExampleTests which extends SolrExampleTestBase which extends AbstractSolrTestCase .
Also this SampleTest.
Also take a look at this and this threads.
First you need to set your Solr Home Directory which contains solr.xml and conf folder containing solrconfig.xml, schema.xml etc.
After that you can use this simple and basic code for Solrj.
File solrHome = new File("Your/Solr/Home/Dir/");
File configFile = new File(solrHome, "solr.xml");
CoreContainer coreContainer = new CoreContainer(solrHome.toString(), configFile);
SolrServer solrServer = new EmbeddedSolrServer(coreContainer, "Your-Core-Name-in-solr.xml");
SolrQuery query = new SolrQuery("Your Solr Query");
QueryResponse rsp = solrServer.query(query);
SolrDocumentList docs = rsp.getResults();
Iterator<SolrDocument> i = docs.iterator();
while (i.hasNext()) {
System.out.println(i.next().toString());
}
I hope this helps.
This is an example for a simple test case. solr is the directory that contains your solr configuration files:
import java.io.IOException; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.util.AbstractSolrTestCase; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.SolrParams; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SolrSearchConfigTest extends AbstractSolrTestCase { private SolrServer server; @Override public String getSchemaFile() { return "solr/conf/schema.xml"; } @Override public String getSolrConfigFile() { return "solr/conf/solrconfig.xml"; } @Before @Override public void setUp() throws Exception { super.setUp(); server = new EmbeddedSolrServer(h.getCoreContainer(), h.getCore().getName()); } @Test public void testThatNoResultsAreReturned() throws SolrServerException { SolrParams params = new SolrQuery("text that is not found"); QueryResponse response = server.query(params); assertEquals(0L, response.getResults().getNumFound()); } @Test public void testThatDocumentIsFound() throws SolrServerException, IOException { SolrInputDocument document = new SolrInputDocument(); document.addField("id", "1"); document.addField("name", "my name"); server.add(document); server.commit(); SolrParams params = new SolrQuery("name"); QueryResponse response = server.query(params); assertEquals(1L, response.getResults().getNumFound()); assertEquals("1", response.getResults().get(0).get("id")); } }
See this blogpost for more info:Solr Integration Tests