Junit的基本使用

72 阅读2分钟

一、目前有的版本:

junit3junit4junit5
jdk<1.5jdk>1.5jdk>1.8
class MyTest extends TestCase{}class MyTest{}class MyTest{}
public test()@Test public test()@Test public test()
官网

二、常用注解:

junit4junit5运行时机备注
@Test@Test添加在测试方法上如果指定异常@Test(expected=Exception.class) 超时验证@Test(timeout=毫秒数)
@Before@BeforeEach每次方法执行前
@After@AfterEach每次方法执行后
@BeforeClass@BeforeAll测试类运行前
@AfterClass@AfterAlll测试类运行后
@ParameterizedTest指定参数进行测试等价于@RunWith(Parameterized.class)配合@ValueSource使用
@ValueSource @ParameterizedTest @ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" }) void palindromes(String candidate) { assertTrue(StringUtils.isPalindrome(candidate)); }
@DisplayName显示的名称
@Ignore忽略方法
@Disabled禁用测试类或者式方法
@Nest用于声明测试中的内部类
其他注解可以参考官网在进行查看官网

伪代码时机示例

//所有测试方法执行伪代码
@BeforeClass
for(Method method:methodList){
    @Before
    method.invock();
    @After
}
@AfterClass

三、常用断言:

相等:assertEquals(100,x)
断言数组相等:assertArrayEquals({1,2,3},x)
浮点断言相等:assertEquals(2.3311,x,0.0001)
为空断言:assertNull(x)
boolean断言:assertTrue(x) assertFalse(x)

四、@Runwith注解

@RunWith:运行器
@RunWith(JUnit4.class) 使用junit4运行
@RunWith(Suite.class) 使用组合测试
@RunWith(Parameterized.class)指定参数进行测试
@RunWith(SpringJUnit4ClassRunner.class) spring中加载spring环境使用
@ContextConfiguration() 配合spring加载配置文件或者配置类注解使用
junit5改为使用@ExtendWith
springboot配合junit可直接使用@SpringbootTest
自定义运行器可参考

五、springboot配合junit使用

1.引入相关依赖

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

2.spring中提供了模拟访问controller接口的功能,通过MockMvc类进行调用,提供可以请求并且对结果进行验证的功能,不需要启动整个模块对controller进行调用。内部创建一个DispatcherServlet示例处理请求。整体配合MockMvcRequestBuilders类进行使用,用于构造请求参数,MockMvcRequestBuilders是一个用于构建MockHttpServletRequestBuilder对象的工具类
MockMVC常用方法: mockMvc.perform执行请求
MockMvcRequestBuilders.post或get构造请求
MockHttpServletRequestBuilder.param或content添加请求参数
MockMvcRequestBuilders.contentType添加请求类型
MockMvcRequestBuilders.accept添加响应类型
ResultActions.andExpect添加结果断言
ResultActions.andDo添加返回结果后置处理
ResultActions.andReturn执行完成后返回相应结果

测试代码:

@RestController
public class AddTestController {
    @RequestMapping(value = "/get")
    public String get(){
        return "string success";
    }
}

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RunWithTest {
    @Autowired
    private ApplicationContext applicationContext;
    MockMvc mockMvc;
    @Before
    public void setUp(){
        mockMvc = MockMvcBuilders.standaloneSetup(AddTestController.class).build();
    }
    @Test
    public void aaa() throws Exception {
        MockHttpServletRequestBuilder param = MockMvcRequestBuilders.get("/get")
                .accept(MediaType.APPLICATION_JSON_UTF8).param("name", "tom");

        ResultActions perform = mockMvc.perform(param);
        //进行结果验证
        MvcResult mvcResult = perform.andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print()).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();
        //获取返回结果
        String contentAsString = response.getContentAsString();
        System.out.println(response);
        System.out.println(contentAsString);
        Assert.assertEquals("string success",contentAsString);
    }
}