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:忽略方法;

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,这里不需要根路径。

猜你喜欢

转载自www.cnblogs.com/t96fxi/p/12418615.html