Skip to content

Commit

Permalink
add unit test knowledge
Browse files Browse the repository at this point in the history
  • Loading branch information
rbmonster committed Apr 11, 2021
1 parent 95661f8 commit a238c60
Show file tree
Hide file tree
Showing 14 changed files with 378 additions and 96 deletions.
25 changes: 24 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,29 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>5.2.1</version>
<scope>test</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.junit.vintage</groupId>-->
<!-- <artifactId>junit-vintage-engine</artifactId>-->
<!-- <scope>test</scope>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.hamcrest</groupId>-->
<!-- <artifactId>hamcrest-core</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
Expand Down Expand Up @@ -117,7 +140,7 @@
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.four.unittest;
package com.four.unittest.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/four/unittest/service/UnitTestService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.four.unittest.service;

import com.four.unittest.controller.UnitController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Slf4j
@Service
public class UnitTestService {


@Autowired
UnitController unitController;

@Autowired
JdbcTemplate jdbcTemplate;

public String testSql() {
log.info("test jdbc update");
return "hehe";
}


public String testJdbcTemplate() {
List<Object> query = jdbcTemplate.query("select * from demo limit 2",
(resultSet, i) -> resultSet.getString(2));
return query.get(0).toString();
}
}
91 changes: 88 additions & 3 deletions src/main/java/com/learning/basic/UNIT_TEST.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ public class JunitDemo {
log.info("hello junit world~");
}
@Test(expected = ArithmeticException.class)
public void testException() {
log.info(String.valueOf(123123/0));
}
@Test(timeout = 2000)
public void testTimeout() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
}
@Ignore
public void testIgnore(){
log.info("this is ignore method");
Expand All @@ -105,14 +116,88 @@ public class JunitDemo {
}
```
### spring相关测试
启动spring容器相关注解

@SpringBootTest注解: 告诉Spring Boot查找一个主要的配置类(例如,一个带有@SpringBootApplication的类),并使用该类来启动Spring应用程序上下文。
- webEnvironment=RANDOM_PORT: 使用webEnvironment = RANDOM_PORT可以使用随机端口启动服务器(用于避免测试环境中的冲突),并使用@LocalServerPort注入端口。

@AutoConfigureMockMvc: 使用Spring的MockMvc,并通过在测试用例上使用@AutoConfigureMockMvc注释,要求为测试用力注入该代码MockMvc代码。

@WebMvcTest : 在测试中,Spring Boot仅实例化了Web层,而不是整个上下文。 在具有多个控制器的应用程序中,甚至可以使用例如@WebMvcTest(HomeController.class)来仅请求实例化一个。
> 可以加快整个applicaiton的启动速度,因为该注解只指定扫描了部分annotation
@Runwith(SpringRunner.class): 说明了改测试用例要在什么环境下进行测试,在Junit4中需要将@RunWith(SpringRunner.class)添加到测试中,否则注释将被忽略。如果使用的是JUnit 5,则无需添加等效的@ExtendWith( SpringExtension.class)(如@SpringBootTest)和其他@…Test注释已使用它进行注释。
- > @ExtendWith( SpringExtension.class) 暂时未研究,主要是@Runwith的拓展类提供能力的增强,应用于Junit5中。
@MockBean:可用于为ApplicationContext中的bean定义Mockito模拟


@DirtiesContext:Spring @DirtiesContext从与测试关联的上下文缓存中删除脏的ApplicationContext


测试用例demo
```
@AutoConfigureMockMvc
@ActiveProfiles(profiles = "test")
@SpringBootTest(classes = UnitTestApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class JunitSpringTestDemo {
@LocalServerPort
private int port;
@Autowired
private UnitTestService unitTestService;
@MockBean
private TransactionTemplate transactionTemplate;
@Before
public void setUp() {
}
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
String forObject = this.restTemplate.getForObject("http://localhost:" + port + "/learning/unit/one", String.class);
System.out.println(forObject);
}
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/unit/one"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("one")));
}
@Test
public void testTemplate() {
String s = unitTestService.testJdbcTemplate();
Assert.assertEquals("return result should be bbb", "bbb", s);
}
}
```

### 参考资料
- [spring boot 单元测试官网文档全说明](https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing)
- [spring test guides](https://spring.io/guides/gs/testing-web/)
- [baeldung spring-boot test](https://www.baeldung.com/spring-boot-testing)
- [spring boot Test Auto-configuration Annotations](https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-test-auto-configuration.html#test-auto-configuration)

## testNG


## Mockito


## BDDMockito

MockitounitTestTower.png
## BDDMockito
4 changes: 0 additions & 4 deletions src/main/java/com/learning/io/bio/SocketDemo.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
package com.learning.io.bio;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.CharBuffer;
import java.util.concurrent.TimeUnit;

/**
* <pre>
Expand Down
37 changes: 37 additions & 0 deletions src/main/resources/ddl/V1.1__Unittest.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

DROP TABLE IF EXISTS `demo`;
CREATE TABLE `demo` (
`demo_id` bigint(20) NOT NULL COMMENT 'ID',
`demo_code` varchar(50) DEFAULT NULL COMMENT '编码',
`demo_name` varchar(50) DEFAULT NULL COMMENT '名称',
`status` varchar(50) DEFAULT NULL COMMENT '状态',
`status_desc` varchar(50) DEFAULT NULL COMMENT '状态描述',
`demo_qty` int(11) DEFAULT NULL COMMENT '数量',
`demo_rate` decimal(10,3) DEFAULT NULL COMMENT '税率',
`start_date` datetime DEFAULT NULL COMMENT '开始时间',
`end_date` datetime DEFAULT NULL COMMENT '结束时间',
`create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_by_name` varchar(50) DEFAULT NULL COMMENT '创建人姓名',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '修改人',
`update_by_name` varchar(50) DEFAULT NULL COMMENT '修改人描述',
`version` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`demo_id`)
) ;


INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (1, 'bbb', 'aaa', 'Y', '启用', 1, 33.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:22:30', 'admin', 'admin', '2019-07-31 20:22:30', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6562301868079329280, 'D201907310019', 'hhe7312', 'Y', '启用', 1, 22.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:04:47', 'admin', 'admin', NULL, NULL, NULL, 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6562301868687503360, 'D201907310020', '随机名称:1518070981', 'Y', '启用', 1, 33.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:04:47', 'admin', 'admin', '2019-07-31 20:04:47', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6562302561842376704, 'D201907310021', '随机名称:-869629984', 'Y', '启用', 1, 22.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:07:32', 'admin', 'admin', '2019-07-31 20:07:32', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6562302976415772672, 'D201907310022', '李四1', 'N', '停用', 1, 33.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:09:11', 'admin', 'admin', '2019-07-31 20:09:11', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6562306324720267264, 'D201907310023', '张三2', 'N', '停用', 1, 22.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:22:30', 'admin', 'admin', '2019-07-31 20:22:30', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6562306325131309056, 'D201907310024', '李四2', 'N', '停用', 1, 33.000, '2019-07-28 00:00:00', '2019-07-28 00:00:00', '2019-07-31 20:22:30', 'admin', 'admin', '2019-07-31 20:22:30', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6566940247236542464, 'D201908130001', '导入测试名称1', 'Y', '', 1, 1.000, NULL, NULL, '2019-08-13 15:16:03', 'admin', 'admin', '2019-08-13 15:16:03', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6567946921279750144, 'D201908160001', 'AAA', 'Y', '', 2, 7.000, '2019-08-16 00:00:00', '2019-08-17 00:00:00', '2019-08-16 09:56:13', 'admin', 'admin', '2019-08-16 09:56:13', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6567947472537124864, 'D201908160002', 'AAA', 'Y', '', 2, 7.000, '2019-08-16 00:00:00', '2019-08-17 00:00:00', '2019-08-16 09:58:24', 'admin', 'admin', '2019-08-16 09:58:24', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6567947711692144640, 'D201908160003', '杀手', 'Y', '', 2, 7.000, '2019-08-16 00:00:00', '2019-08-17 00:00:00', '2019-08-16 09:59:21', 'admin', 'admin', '2019-08-16 09:59:21', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6567952911945433088, 'D201908160004', 'AAA', 'Y', '', 2, 7.000, '2019-08-16 00:00:00', '2019-08-17 00:00:00', '2019-08-16 10:20:01', 'admin', 'admin', '2019-08-16 10:20:01', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6567952973857554432, 'D201908160005', 'AAA', 'Y', '', 2, 7.000, '2019-08-16 00:00:00', '2019-08-17 00:00:00', '2019-08-16 10:20:16', 'admin', 'admin', '2019-08-16 10:20:16', 'admin', 'admin', 0);
INSERT INTO `demo`(`demo_id`, `demo_code`, `demo_name`, `status`, `status_desc`, `demo_qty`, `demo_rate`, `start_date`, `end_date`, `create_time`, `create_by`, `create_by_name`, `update_time`, `update_by`, `update_by_name`, `version`) VALUES (6567953486372143104, 'D201908160006', 'AAA', 'Y', '', 2, 7.000, '2019-08-16 00:00:00', '2019-08-17 00:00:00', '2019-08-16 10:22:18', 'admin', 'admin', '2019-08-16 10:22:18', 'admin', 'admin', 0);
3 changes: 3 additions & 0 deletions src/main/resources/ddl/init_schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CREATE SCHEMA IF NOT EXISTS `unit-test`;

SET SCHEMA `unit-test`;
45 changes: 45 additions & 0 deletions src/test/java/DataJdbcTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import com.four.unittest.UnitTestApplication;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.List;

@Slf4j
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = UnitTestApplication.class)
@DataJdbcTest
public class DataJdbcTests {

//
// @Autowired
// UnitTestService unitTestService;
//
// @Test
// public void setUnitTestService(){
// String s = unitTestService.testJdbcTemplate();
// Assert.notNull("", s);
// }

@Autowired
JdbcTemplate jdbcTemplate;

@Test
public void testJdbc() {
List<String> query = jdbcTemplate.query("select * from demo limit 2",
(resultSet, i) -> resultSet.getString(2));
log.info(Arrays.toString(query.toArray()));
Assert.assertEquals("", 2, CollectionUtils.size(query));
}

}
13 changes: 13 additions & 0 deletions src/test/java/JunitDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import org.junit.Test;
import org.junit.*;

import java.util.concurrent.TimeUnit;

@Slf4j
public class JunitDemo {

Expand All @@ -21,6 +23,17 @@ public void testDemo() {
log.info("hello junit world~");
}


@Test(expected = ArithmeticException.class)
public void testException() {
log.info(String.valueOf(123123/0));
}

@Test(timeout = 2000)
public void testTimeout() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
}

@Ignore
public void testIgnore(){
log.info("this is ignore method");
Expand Down
19 changes: 10 additions & 9 deletions src/test/java/JunitSpringTestDemo.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import com.four.filterinterceptor.interceptor.TestInterceptorController;
import com.four.transaction.TransactionApplication;
import com.four.unittest.UnitTestApplication;
import com.four.unittest.service.UnitTestService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand All @@ -17,8 +17,6 @@
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
Expand Down Expand Up @@ -48,11 +46,8 @@ public class JunitSpringTestDemo {
@LocalServerPort
private int port;

@MockBean
private JdbcTemplate jdbcTemplate;

@MockBean
private PlatformTransactionManager platformTransactionManager;
@Autowired
private UnitTestService unitTestService;

@MockBean
private TransactionTemplate transactionTemplate;
Expand Down Expand Up @@ -81,4 +76,10 @@ public void shouldReturnDefaultMessage() throws Exception {
.andExpect(status().isOk())
.andExpect(content().string(containsString("one")));
}

@Test
public void testTemplate() {
String s = unitTestService.testJdbcTemplate();
Assert.assertEquals("return result should be bbb", "bbb", s);
}
}
Loading

0 comments on commit a238c60

Please sign in to comment.