web系统中的一些测试方法总结

源自Spring in Action的一些总结

(1)引入junit进行测试

1、导包

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.11</version>
   <scope>test</scope>
</dependency>
//测试文件不放在src/test下的话就不要加scope了 否则找不到@test注解

2、代码中添加@test注解(@test注解应用在方法上),这里我们主要了解Junit单元测试中Assert断言的使用。

//导入
import org.junit.Test;
import static org.junit.Assert.*
// egs:
assertEquals("home",contolller.home())  // 查看两个对象是否相等
assertNull(object) // 查看对象是否为空
...

(2)使用SpringMVC提供的测试方法,可以不用启动服务器进行控制器测试非常的方便快捷

1、添加依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>4.3.14.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
   <artifactId>mockito-all</artifactId>
   <version>1.10.19</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.11</version>
</dependency>

2、代码中使用

import org.junit.Test;
import static org.springframework.test.web.servlet.*;
import static org.mockito.Mockito.*;  //如果代码中使用了mock()方法需导入
@Test
public void shouldShowRecentSpittles() throws Exception{
     List<Spittle> spittles = creatSpittles(20);
     SpittleRepository mockRepository = mock(SpittleRepository.class);
     when(mockRepository.findSpittles(Long.MAX_VALUE,20))
             .thenReturn(spittles);
     SpittleController controller = new SpittleController(mockRepository);
     //Mock Spring MVC 
     MockMvc mockMvc = standaloneSetup(controller).setSingleView(
             new InternalResourceView("/WEB-INF/views/spittles.jsp")
     ).build();
     //对spittles发起get请求
     mockMvc.perform(get("/spittles"))		
             .andExpect(view().name("spittles"))  //期待视图名称是 spittles
             .andExpect(model().attributeExists("spittleList")) //   返回的模型数据包含spittleList
       	     .andExpect(model().attribute("spittleList",hasItems(spittles.toArray())));

 }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值