021-Spring Boot 測試

weixin_33982670發表於2018-04-06

一。概述

二、Junit方式使用

2.1、基本使用

  eclipse在新建的類上,右鍵→new→Junit Test Case,修改一下Source folder,選擇src/test/java,下一步,選擇需要測試的方法即可.

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));
    }
}

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"));
    }
}

 

相關文章