數(shù)據(jù)層的測試
數(shù)據(jù)主要使用Mybatis,因此注入的時(shí)候也只需要引入Mybatis相關(guān)的配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-dao.xml" })
public class SeckillDaoTest {
// 注入Dao實(shí)現(xiàn)類依賴
@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);
}
}
業(yè)務(wù)層測試
業(yè)務(wù)層會(huì)涉及到多表的操作,因此需要引入事務(wù)。而為了方便重復(fù)測試,添加回滾功能。
@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);
}
}
控制層測試
控制層主要模擬用戶請求,這里設(shè)計(jì)到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"));
}
}
|