1.采用spring提供的单元测试通过注入方式
加入单元测试包,可以方便控制事物、回滚
2.实现TestCase单元测试
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
加入单元测试包,可以方便控制事物、回滚
package com.unit.mongo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.home.model.mongo.Person;
import com.home.service.mongo.IPersonBiz;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class TestMongo {
@Autowired
private IPersonBiz personBiz;
@Test
public void test() {
findWithPage();
}
/**
* 测试mongoDB分页查询
*/
public void findWithPage(){
Pageable pageable = new PageRequest(0, 30);
Map<String, Object>params = new HashMap<String, Object>();
params.put("name", "tom");
List<Person> persons = personBiz.findWithPage(params, pageable);
for(Person person: persons){
System.out.println(person.toString());
}
}
@Rollback
public void save(){
}
}
2.实现TestCase单元测试
package com.unit.mongo;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import com.home.model.mongo.Person;
/**
* 继承TestCase不依赖与spring-test包
* @author li
*/
public class TestWithCase extends TestCase {
public ApplicationContext ctx = null;
/**
* 测试一次初始化Spring容器
*/
@Before
protected void setUp() throws Exception {
super.setUp();
ctx = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
}
/**
* 需要手动获取bean
* @return
*/
private MongoOperations getMongoOper(){
return (MongoOperations)ctx.getBean("mongoTemplate");
}
@Test
public void test() {
MongoOperations mongo = this.getMongoOper();
List<Person> persons = mongo.findAll(Person.class);
for(Person person: persons){
System.out.println(person.toString());
}
}
}