021-Spring Boot 测试,Junit方式使用,mock方式,Controller测试

一。概述

二、Junit方式使用

2.1、基本使用

  eclipse在新建的类上,右键→new→Junit Test Case,修改一下Source folder,选择src/test/java,下一步,选择需要测试的方法即可.

  idea mac上在类内,cmd+shift+T,即可

1》在测试类开头增加

@RunWith(SpringRunner.class)
@SpringBootTest

  示例如下

待测试类

@Repository
public class UserDao {
    public Integer addUser(String username) {
        System.out.println("user dao adduser [username="+username+"]");
        if(username==null) {
            return 0;
        }
        return 1;
    }
}
View Code

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {

    @Autowired
    private UserDao userDao;

    @Test
    public void testAddUser() {
        Assert.assertEquals(Integer.valueOf(1), userDao.addUser("s"));
        Assert.assertEquals(Integer.valueOf(0), userDao.addUser(null));
    }
}
View Code

2.2、加载测试Bean

1》增加测试configuration

/**
 * 只能测试环境下使用
 * 只能用@TestConfiguration 不能使用@Configuration
 *
 */
@TestConfiguration
public class TestBeanConfiguration {

    @Bean
    public Runnable createRunnable() {
        return ()->{};
    }
}

2》在调用类处增加如下

@RunWith(SpringRunner.class)
@SpringBootTest(classes=TestBeanConfiguration.class)

2.3、测试配置文件

可以读取src/main/resources,也可以使用src/test/resources,如果有相同的优先使用测试环境配置,

@RunWith(SpringRunner.class)
@SpringBootTest
public class EnvTest {
    @Autowired
    private ConfigurableEnvironment env;

    @Test
    public void testEnv() {
        Assert.assertEquals("springboot", env.getProperty("app.name"));
    }
}

2.4、指定配置项

@RunWith(SpringRunner.class)
@SpringBootTest(properties= {"app.version=1.0.0"})

或者

    @Before
    public void init() {
        EnvironmentTestUtils.addEnvironment(env, "app.admin.name=admin");
    }

三、mock方式

3.1、测试接口,提前预估一些量

@RunWith(SpringRunner.class)
public class UserMapperTest {

    @MockBean
    private UserMapper usermapper;

    @Before
    public void init() {
        BDDMockito.given(usermapper.createUser("admin")).willReturn(Integer.valueOf(1));
        BDDMockito.given(usermapper.createUser("")).willReturn(Integer.valueOf(0));
        BDDMockito.given(usermapper.createUser(null)).willThrow(NullPointerException.class);
    }

    @Test(expected = NullPointerException.class)
    public void testCreateUser() {
        Assert.assertEquals(Integer.valueOf(1), usermapper.createUser("admin"));
        Assert.assertEquals(Integer.valueOf(0), usermapper.createUser(""));
        Assert.assertEquals(Integer.valueOf(0), usermapper.createUser(null));
    }
}

四、Controller测试

第一种使用:TestRestTemplate 

1》需要测试类增加

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

2》需要使用TestRestTemplate 需运行在web环境

    @Autowired
    private TestRestTemplate restTemplate;

示例:

需要被测试的Controller

@RestController
public class BookController {
    @GetMapping("/book/home")
    public String home() {
        System.out.println("/book/home url is invode.");
        return "home";
    }

    @GetMapping("/book/show")
    public String show(String id) {
        System.out.println("/book/show url is invode.");
        return "book" + id;
    }
}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BookControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testHome() {
        String object = restTemplate.getForObject("/book/home", String.class);
        Assert.assertEquals("home", object);
    }
    
    @Test
    public void testShow() {
        String object = restTemplate.getForObject("/book/show?id=100", String.class);
        Assert.assertEquals("book100", object);
    }
}

第二种使用:MockMvc

1》配置

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)

2》程序使用

    @Autowired
    private MockMvc mvc;

示例,对以上示例测试

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)
public class BookControllerTest2 {

    @Autowired
    private MockMvc mvc;

    @Test
    public void testHome() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/book/home")).andExpect(MockMvcResultMatchers.status().isOk());
        mvc.perform(MockMvcRequestBuilders.get("/book/home")).andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("home"));
    }

    @Test
    public void testShow() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/book/show").param("id", "400"))
                .andExpect(MockMvcResultMatchers.status().isOk());
        mvc.perform(MockMvcRequestBuilders.get("/book/show").param("id", "400"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("book400"));
    }
}

现将BookController改造,增加了Dao使用

@RestController
public class BookController {
    @Autowired
    private UserDao userDao;
    @GetMapping("/book/home")
    public String home() {
        System.out.println("/book/home url is invode.");
        return "home";
    }

    @GetMapping("/book/show")
    public String show(String id) {
        System.out.println("/book/show url is invode.");
        userDao.addUser("");
        return "book" + id;
    }
}

现在使用第二种方式,不能通过,因为WebMvcTest(controllers = BookController.class)方式只是加载指定类,没有加载Spring全部容器,所以第二种只能测试controller,依赖需要自己mock

使用第一种方式,加载Spring全部容器。

如果使用第二种,还需要加载全部容器

第三种、MockMv加载全部容器

  @SpringBootTest不能和@WebMvcTest同时使用

  如果使用MockMvc对象的话需要使用一下方式

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class BookControllerTest3 {

    @Autowired
    private MockMvc mvc;

    @Test
    public void testHome() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/book/home")).andExpect(MockMvcResultMatchers.status().isOk());
        mvc.perform(MockMvcRequestBuilders.get("/book/home")).andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("home"));
    }
}

 

posted @ 2018-04-06 14:27  bjlhx15  阅读(629)  评论(0编辑  收藏  举报
Copyright ©2011~2020 JD-李宏旭