Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I use Spring mongo template in a Spring MVC app and JUnit 4.8.2 for unit tests. Just create a bean for your mongoTemplate and use Autowired to inject it in your classes. As for the tests, follow these steps:</p> <p>1.Create a new JUnit test case (right-click on your class in the Package Explorer, then new->JUnit Test Case). It will create a test method for each method of your class you specify.</p> <p>2.Now you'll have your tests at <em>src/test/java</em> and yor resources at <em>src/test/resources</em>. It is better if you create a spring config file just for the tests so you can point the tests to a local mongodb instance and your application to perhaps a Development mongoDB instance. So create a the config file at <em>src/test/resources</em> and name it <em>testSpringConfig.xml</em> or whatever and create the bean there:</p> <pre><code> &lt;mongo:db-factory dbname="myDB" host="localhost" username="myDbUser" password="myPass"/&gt; &lt;beans:bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"&gt; &lt;beans:constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /&gt; &lt;/beans:bean&gt; &lt;beans:bean id="mongoTemplateLibrary" class="org.springframework.data.mongodb.core.MongoTemplate"&gt; &lt;beans:constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /&gt; &lt;/beans:bean&gt; </code></pre> <p>3.In your test class, use annotations to reference your config file:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/testSpringConfig.xml"}) public class MyDaoTest { </code></pre> <p>4.Once you have your test class set up, inject the mongo template </p> <pre><code>@Autowired @Qualifier("mongoTemplate") private MongoTemplate mongoTemplate; </code></pre> <p>5.Now yo can use it to insert/remove/find/update directly to mongo (although this would be a integration test more than a unit test) For example, you can remove the objects you inserted in your tests using the Tear Down method:</p> <pre><code>@After public void tearDown() { mongoTemplate.remove(myObject); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload