zoukankan      html  css  js  c++  java
  • springboot(3) junit单元测试

    一·Junit的使用

    1.1 添加junit的依赖

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
    </dependency>

    1.2 基础使用

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class GirlServiceTest {
        @Autowired
        GirlService girlService;
        
        @Test
        public void findOneTest() {
            Girl girl = girlService.findOne(8);
            Assert.assertEquals(new Integer(10), girl.getAge());
        }
    }

    Run as ->Junit test 后可在控制台查看执行结果

    1.3 注解说明

    • @RunWith:标识为Junit的运行环境
    • @SpringBootTest:获取启动类,加载配置,确定装载springboot
    • @Test
    • @BeforeClass:针对所有测试,只执行一次,且必须为static void;
    • @AfterClass:针对所有测试,只执行一次,且必须为static void;
    • @Before:每个测试方法前都会执行的方法;
    • @After:每个测试方法前都会执行的方法;
    • @Ignore:忽略方法;
    • @Transactional:执行完成后会自动回滚数据库操作,可以防止测试数据修改数据库

    1.4 断言

    断言就是判断是否和期望值相符合

    • Assert.assertEquals 对比两个值相等
    • Assert.assertNotEquals 对比两个值不相等
    • Assert.assertSame 对比两个对象的引用相等
    • Assert.assertArrayEquals 对比两个数组相等
    • Assert.assertTrue 验证返回是否为真
    • Assert.assertFlase 验证返回是否为假
    • Assert.assertNull 验证null
    • Assert.assertNotNull 验证非null

    1.5 WEB模拟测试

    使用MockMvc对web进行测试

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class GirlControllerTest {
        @Autowired
        private MockMvc mvc;
        
        @Test
        public void girlList() throws Exception {
            mvc.perform(MockMvcRequestBuilders.get("/girls/getAge/8"))
                .andExpect(MockMvcResultMatchers.status().isOk());
                //.andExpect(MockMvcResultMatchers.content().string("abc"));
        }
    }

    @AutoConfigureMockMvc:配合上@Autowired就可以自动的注册所有添加@Controller或者@RestController的路由的MockMvc了

    问题:/girl/girls/getAge/8返回404,因为在application.yml中context-path=girl,这里不需要根路径。

  • 相关阅读:
    Eclipse Java开发环境配置 + memcached + maven
    sqlserver数据库自动备份
    从表A中选择部分字段插入到表B
    电信IOT平台关于产品profile插件的添加流程
    SQLServer查询耗时sql语句
    net core 包管理
    byte[] 截串操作
    关于kafka启动失败问题
    springboot 搭建maven项目
    C# MongoDB学习之路(一)
  • 原文地址:https://www.cnblogs.com/t96fxi/p/12418615.html
Copyright © 2011-2022 走看看