參考: http://blog.csdn.net/you8626/article/details/41980749
http://blog.csdn.net/u013803262/article/details/52253825?locationNum=6
1.maven中需引入正確的依賴。注意不要出現空格
1 <dependency> 2 <groupId>org.springframework</groupId> 3 <artifactId>spring-test</artifactId> 4 <version>4.2.4.RELEASE</version> 5 </dependency>
2.在測試用例中
@RunWith(SpringJUnit4ClassRunner.class)
SpringJUnit支持,由此引入Spring-Test框架支持,讓測試運行於Spring測試環境,Spring框架在org.springframework.test.annotation 包中提供了常用的Spring特定的注解集。
@ContextConfiguration(locations = "classpath:applicationContext.xml")
導入配置文件。這是Spring的注解。運行時會先加載applicationContext.xml文件,掃描所有的包,會把注解的bean全部加載到spring容器中。
@Resource
會去拿到MongoTemplate這個bean,就可以用了
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(locations={"classpath:spring/messagecenter/applicationContext.xml"}) 3 public class RecipeTest { 4 @Resource 5 private MongoTemplate mongoTemplate; 6 7 @Test 8 public void testRecipe(){ 9 MessageHistory messageHistory = new MessageHistory(); 10 mongoTemplate.save(messageHistory); 11 12 } 13 }