SSM项目各层单元测试

数据层的测试

数据主要使用Mybatis,因此注入的时候也只需要引入Mybatis相关的配置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-dao.xml" })
public class SeckillDaoTest {

	// 注入Dao实现类依赖
	@Resource
	private SeckillDao seckillDao;

	@Test
	public void testReduceNumber() {
		long seckillId=1000;
        Date date=new Date();
        int updateCount=seckillDao.reduceNumber(seckillId,date);
        System.out.println(updateCount);
	}
}

业务层测试

业务层会涉及到多表的操作,因此需要引入事务。而为了方便重复测试,添加回滚功能。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SeckillServiceImplTest {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SeckillService seckillService;

	@Test
	public void testGetSeckillList() {
		List<Seckill> seckills = seckillService.getSeckillList();
		System.out.println(seckills);
	}
}

控制层测试

控制层主要模拟用户请求,这里设计到http请求,我们可以使用mock测试

@WebAppConfiguration
@ContextConfiguration({ "classpath:spring/spring-dao.xml", 
	"classpath:spring/spring-service.xml",
	"classpath:spring/spring-web.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SeckillControllerTest  {

	@Autowired
	protected WebApplicationContext context;
	
	private MockMvc mockMvc;
	private String listUrl = "/seckill/list";
	private String detailUrl = "/seckill/{seckillId}/detail";
	private String expserUrl = "/seckill/{seckillId}/exposer";
	private long seckillId = 1000L;

	@Before
	public void setUp() {
		this.mockMvc = webAppContextSetup(this.context).alwaysExpect(status().isOk()).alwaysDo(print()).build();
	}

	@Test
	public void testList() throws Exception {
		this.mockMvc.perform(get(listUrl)).andExpect(view().name("list"));
	}

	@Test
	public void testExistDetail() throws Exception {
		this.mockMvc.perform(get(detailUrl, seckillId)).andExpect(view().name("detail"))
				.andExpect(model().attributeExists("seckill"));
	}
}

猜你喜欢

转载自my.oschina.net/kimisme/blog/1635196
今日推荐