转载:https://my.oschina.net/kimisme/blog/1635196

数据层的测试

数据主要使用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)//黄色的注解是在spring4.2前的版本可以,4.2后的就过时了。
@Transactional

//4.2后的注解是下面红色的配置

@Transactional(transactionManager = "transactionManager ")
@Rollback(value = true)

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//黄色是spring4.2前的;4.2后的见上面的红色配置部分
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"));
	}
}
posted on 2018-11-29 21:08  navyhj  阅读(1988)  评论(0)    收藏  举报