Linking

Capturing Life & Tech

  • 主页
  • 随笔
  • 关于我
所有文章 外链

Linking

Capturing Life & Tech

  • 主页
  • 随笔
  • 关于我

unit-test-in-SpringBoot-with-login-token

阅读数:次 2022-09-17
字数统计: 1.1k字   |   阅读时长≈ 6分

classify

precondition

test class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class ClsName {

// bind the above RANDOM_PORT
@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

private String token;

}

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!-- jUnit test start -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
<version>5.9.0</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.22</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test-autoconfigure</artifactId>
<version>2.6.6</version>
<scope>test</scope>
</dependency>
<!-- jUnit test end -->

with login, use token

CRUD: create read update delete

auto login beforeEach

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 模拟登录
*/
@BeforeEach
public void setLoginUser() throws MalformedURLException {
LoginBodyEntity fdLoginBodyEntity = new LoginBodyEntity();
loginBodyEntity.setUsername("username");
loginBodyEntity.setPassword("password");
ResponseEntity<AjaxResult> response = restTemplate.postForEntity(
new URL("http://localhost:" + port + "/login").toString, loginBodyEntity, AjaxResult.class);

token = (String) Objects.requireNonNull(response.getBody()).get("data");
}

create

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 测试增加nbhd
* name唯一性
* 新建的各项数据合理性
*/
@Test
@DisplayName("test add unique name success")
void addNbhd() throws Exception {
AddModel aEntity = new AddModel();
aEntity.setName("name");

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
HttpEntity<AddModel> entity = new HttpEntity<>(aEntity, headers);

ResponseEntity<AjaxResult> response = restTemplate.postForEntity(
new URL("http://localhost:" + port + "/add").toString, entity, AjaxResult.class);

System.out.println("code: " + Objects.requireNonNull(response.getBody()).get("code") + "; msg: "
+ Objects.requireNonNull(response.getBody()).get("msg"));
assertEquals(200, Objects.requireNonNull(response.getBody()).get("code"));
assertEquals("操作成功", response.getBody().get("msg"));
}

read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 测试 list
*/
@Test
public void getList() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
HttpEntity<String> requestHeader = new HttpEntity<>(headers);

String urlTemplate = UriComponentsBuilder.fromHttpUrl(new URL("http://localhost:" + port + "/list").toString, port))
.queryParam("pageNum", "1")
.queryParam("pageSize", "12")
.queryParam("name", "nbhd2")
// .queryParam("orderByColumn", "arm_type")
// .queryParam("isAsc", "desc")
.build()
.toString();

ResponseEntity<TableDataInfo> response = restTemplate.exchange(
urlTemplate, HttpMethod.GET, requestHeader, TableDataInfo.class);

System.out.println("size is " + Objects.requireNonNull(response.getBody()).getData().getList().size()
+ "; nbhd: " + Objects.requireNonNull(response.getBody()).getData().getList().toString());
assertEquals(200, Objects.requireNonNull(response.getBody()).getCode());
assertThat("row", Long.parseLong(String.valueOf(response.getBody().getData().getList().size())), greaterThan(0L));
}

/**
* test detail getInfo
*/
@Test
public void getDetail() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);

HttpEntity<String> requestHeader = new HttpEntity<>(headers);

String urlTemplate = UriComponentsBuilder.fromHttpUrl(new URL("http://localhost:" + port + "/12").toString, port))
.build()
.toString();

ResponseEntity<AjaxResult> response = restTemplate.exchange(
urlTemplate, HttpMethod.GET, requestHeader, AjaxResult.class);

System.out.println("nbhd: " + Objects.requireNonNull(response.getBody()).get("data").toString());
assertEquals(200, Objects.requireNonNull(response.getBody()).get("code"));
assertEquals("操作成功", response.getBody().get("msg"));
}

update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 测试edit
*/
@Test
@DisplayName("test edit success")
void testEdit() throws Exception {
EModel eModel = new EModel();
eModel.setId(3L);
eModel.setName("newName");

HttpEntity<EModel> entity = new HttpEntity<>(eModel, headers);

ResponseEntity<AjaxResult> response1 = restTemplate.exchange(
new URL("http://localhost:" + port + "/edit").toString, HttpMethod.PUT, entity1, AjaxResult.class);

System.out.println("msg: " + Objects.requireNonNull(response1.getBody()).get("msg"));
assertEquals(200, Objects.requireNonNull(response1.getBody()).get("code"));
assertEquals("操作成功", response1.getBody().get("msg"));
}

/**
* 测试edit
* json实例
*/
@Test
@DisplayName("test edit unique name success")
void editWithJson() throws Exception {
List<String> list1 = new ArrayList<>();
JSONObject json1 = new JSONObject();
json1.put("sfId", 1);
json1.put("weight", 50);
list1.add(String.valueOf(json1));
json1.put("sfId", 2);
json1.put("weight", 50);
list1.add(String.valueOf(json1));

String urlTemplate1 = UriComponentsBuilder.fromHttpUrl(
new URL("http://localhost:" + port + "/edit?id={id}&name={name}&jsonStr={jsonStr}").toString, port))
.build()
.toString();

String name1 = "nameAdd3";
ResponseEntity<AjaxResult> response1 = restTemplate.exchange(
urlTemplate1, HttpMethod.PUT, requestHeader, AjaxResult.class, 12, name1, list1.toString());

System.out.println("msg: " + Objects.requireNonNull(response1.getBody()).get("msg"));
assertEquals(200, Objects.requireNonNull(response1.getBody()).get("code"));
assertEquals("操作成功", response1.getBody().get("msg"));
}

delete

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 测试删除
*/
@Test
@DisplayName("test del success")
void testDel() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
HttpEntity<String> requestHeader = new HttpEntity<>(headers);

String idsStr = "15,16";
String urlTemplate = UriComponentsBuilder.fromHttpUrl(new URL("http://localhost:" + port + "/{ids}").toString, port))
.build()
.toString();

ResponseEntity<AjaxResult> response = restTemplate.exchange(
urlTemplate, HttpMethod.DELETE, requestHeader, AjaxResult.class, idsStr);

assertEquals(200, Objects.requireNonNull(response.getBody()).get("code"));
assertEquals("操作成功", response.getBody().get("msg"));
}

advantages

  • test all changed codes work well one time
  • 本文作者: Linking
  • 本文链接: https://linking.fun/2022/09/17/unit-test-in-SpringBoot-with-login-token/
  • 版权声明: 版权所有,转载请注明出处!
  • unit-test
  • cs

扫一扫,分享到微信

record something about disk common used
gitea内网服务安装及外网映射
  1. 1. classify
    1. 1.1. precondition
      1. 1.1.1. test class
      2. 1.1.2. pom.xml
    2. 1.2. with login, use token
      1. 1.2.1. auto login beforeEach
      2. 1.2.2. create
      3. 1.2.3. read
      4. 1.2.4. update
      5. 1.2.5. delete
  2. 2. advantages
© 2015-2026 Linking
GitHub:hexo-theme-yilia-plus by Litten
本站总访问量次 | 本站访客数人
  • 所有文章
  • 外链

tag:

  • weather
  • 需求
  • essay
  • basketball
  • olympic
  • nginx
  • APPScan
  • SQl盲注
  • xss
  • Ajax
  • ajax
  • ai
  • agent
  • openclaw
  • ccf
  • Nginx
  • HTML5
  • html5
  • hmtl5
  • sse
  • JavaScriptCore
  • Oracle
  • operation
  • Linux
  • deploy
  • Mac Office
  • markdown
  • ListView
  • GridView
  • MySQL
  • 慢查询
  • mongodb
  • 转置
  • thought
  • network
  • ubuntu
  • NetworkManager
  • RFKill
  • Netplan
  • avatar
  • cocoa
  • blog
  • Gitalk
  • container
  • macvlan
  • docker
  • oracle
  • cookie
  • patch
  • gitea
  • git
  • iOS
  • https
  • 多线程
  • bundle
  • 兼容性
  • HTTP
  • 绘图
  • cs
  • java
  • 效率
  • 快捷键
  • route
  • nodejs
  • pip
  • arcgis
  • arcgis 建模
  • 标识
  • redis
  • read
  • bookList
  • running
  • showdoc
  • disk
  • unit-test
  • D.Wade
  • thoughts
  • duoduo
  • Python
  • python
  • tomcat
  • 读书节
  • session
  • jdk
  • war
  • 加班
  • Android onclick事件监听
  • 正则
  • 手机品牌匹配
  • ntp
  • OpenLayers
  • Geoserver
  • wechat
  • 微信公众号
  • 爬虫
  • WeChat
  • 张靓颖
  • 动漫
  • vpn
  • PPT
  • MarkDown
  • plan
  • 朱赟
  • 极客时间专栏
  • 极客邦
  • 模块化
  • MVC
  • excel
  • NBA
  • kobe
  • team
  • crawler
  • 进度条
  • ssl
  • book
  • anti-stealing-link
  • Agentic Engineering
  • Vibe Coding
  • Software 3.0
  • Andrej Karpathy
  • LLM
  • Programming

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia-plus根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

  • GitHub Trending
  • OpenAI ChatGPT
  • Gitee码云
  • 简书
  • CSDN