spring boot test的简单使用


spring boot test的简单使用

相信大家对于junit都不陌生吧,具体我就不介绍了,下面直接上代码吧

package com.zxl.examples.controller;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by Administrator on 2017/8/2.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void test() {
        ResponseEntity response = this.restTemplate.getForEntity(
                "/hello/{name}", String.class, "testName");
        System.out.println(response.getBody());
        Assert.assertTrue("hello testName".equals(response.getBody()));
    }

}

package com.zxl.examples.controller;

import com.zxl.examples.entity.User;
import com.zxl.examples.service.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import static org.mockito.BDDMockito.given;

/**
 * Created by Administrator on 2017/8/2.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @MockBean
    private UserRepository userRepository;;

    /**
     * 模拟返回的假数据-->覆盖真实返回的数据
     */
    @Before
    public void setup() {
        given(this.userRepository.
                findOne(5L)
        ).willReturn(
                new User("test", "testName","123456"));
    }



    @Test
    public void test() {
        ResponseEntity response =this.restTemplate.getForEntity("/users/{id}",
                String.class, 5L);
        System.out.println(response.getBody());
    }
}
package com.zxl.examples.controller;

import com.zxl.examples.entity.User;
import com.zxl.examples.service.UserRepository;
import com.zxl.examples.service.UserSerivceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Created by Administrator on 2017/8/3.
 * WebMvcTest中引入控制类中(此处为UserController.class)的Autowired依赖有几个这里也要相应的配置与之一一对应的@MockBean,否则会报缺失依赖的注入错误
 *
 *
 */
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTests {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private UserSerivceImpl userService;

    @MockBean
    UserRepository userRepository;

    @Test
    public void getVehicleShouldReturnMakeAndModel() throws Exception {
        User returnUser = new User("5", "5","5");
        returnUser.setId(5L);
        given(this.userRepository.findOne(5L))
                .willReturn(returnUser);

        byte[] result = this.mvc.perform(get("/users/{id}",5L)
                .accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsByteArray();
        System.out.print(new String(result)+"----------");
    }


}
package com.zxl.examples.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxl.examples.entity.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.json.JacksonTester;

import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by Administrator on 2017/8/3.
 */
public class UserJsonTest {

    private JacksonTester json;

    @Before
    public void setup() {
        ObjectMapper objectMapper = new ObjectMapper();
        // Possibly configure the mapper
        JacksonTester.initFields(this, objectMapper);
    }

    @Test
    public void serializeJson() throws IOException {
        User user =
                new User("Honda", "Civic","123456");

//        assertThat(this.json.write(user))
//                .isEqualToJson("User.json");

        assertThat(this.json.write(user))
                .hasJsonPathStringValue("@.username");

        assertThat(this.json.write(user))
                .extractingJsonPathStringValue("@.username")
                .isEqualTo("Honda");
    }

    @Test
    public void deserializeJson() throws IOException {
        String content = "{\"username\":\"Ford\",\"name\":\"Focus\"}";

        assertThat(this.json.parse(content))
                .isEqualTo(new User("Ford", "Focus","123456"));

        assertThat(this.json.parseObject(content).getUsername())
                .isEqualTo("Ford");
    }
}
package com.zxl.examples.controller;

import com.zxl.examples.entity.User;
import com.zxl.examples.service.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by Administrator on 2017/8/3.
 */
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository repository;

    @Test
    public void findByUsernameShouldReturnUser() {
        //初始化user数据
        this.entityManager.persist(new User("5", "5","5"));
        User user = this.repository.findByUsername("5").get(0);

        assertThat(user.getName()).isEqualTo("5");
        assertThat(user.getUsername()).isEqualTo("5");
    }


}
package com.xuexin.xcloud.print.web.api;

import com.xuexin.xcloud.PrintAPIStart;
import com.xuexin.xcloud.print.entity.common.ResultBean;
import com.xuexin.xcloud.print.entity.util.JsonUtil;
import com.xuexin.xcloud.print.entity.util.StringUtils;
import com.xuexin.xcloud.print.entity.util.XuexinConstants;
import com.xuexin.xcloud.print.webapi.entity.PrintUserActionLogWeb;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

/**
 * Created by Administrator on 2017/7/7.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PrintAPIStart.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PrintUserActionLogControllerTest {
    private int port = 10515;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "");
    }

    @Test
    public void updPrintCodeStatusByPrintCode() {
//        String username = "100011";
        String username = "";
        String printcode = "54a20";
        Long printTime = 601L;
        Integer printCount = 6;
        Integer printType = 1;
        Double payAmount = 1.11D;
        Integer payType = 1;
        String machineCode = "A9539 - BB3BA - 062AA - 5JBRB - JENCP";

        StringBuffer valiStr = new StringBuffer();
        if(!StringUtils.isNull(username)){
            valiStr.append("username=");
            valiStr.append(username);
            valiStr.append("&");
        }
        if(!StringUtils.isNull(printcode)){
            valiStr.append("printcode=");
            valiStr.append(printcode);
            valiStr.append("&");
        }
        valiStr.append("printTime=");
        valiStr.append(printTime);
        valiStr.append("&");
        valiStr.append("printCount=");
        valiStr.append(printCount);
        valiStr.append("&");
        valiStr.append("printType=");
        valiStr.append(printType);
        valiStr.append("&");
        valiStr.append("payAmount=");
        valiStr.append(payAmount);
        valiStr.append("&");
        valiStr.append("payType=");
        valiStr.append(payType);
        valiStr.append("&");
        valiStr.append("machineCode=");
        valiStr.append(machineCode);
        valiStr.append("&");
        valiStr.append(XuexinConstants.XUEXIN_MD5_SIGN);
        String sign = StringUtils.getMD5Str(valiStr.toString());

        PrintUserActionLogWeb printUserActionLog = new PrintUserActionLogWeb();
        if(!StringUtils.isNull(printcode)){
            printUserActionLog.setPrintcode(printcode);
        }
        printUserActionLog.setUsername(username);
        printUserActionLog.setMachineCode(machineCode);
        printUserActionLog.setPayAmount(payAmount);
        printUserActionLog.setPayType(payType);
        printUserActionLog.setPrintCount(printCount);
        printUserActionLog.setPrintType(printType);
        printUserActionLog.setPrintTime(printTime);
        printUserActionLog.setSign(sign);

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity formEntity = new HttpEntity(JsonUtil.toJson(printUserActionLog), headers);
        ResponseEntity response = template.postForEntity(base.toString() + "/bgtracking/add",formEntity ,String.class);
        System.out.println(response.getBody());
        Assert.assertTrue(JsonUtil.fromJson(response.getBody(), ResultBean.class).isSuccess());
    }
}
package com.xuexin.xcloud.print.web.api;

import com.xuexin.xcloud.PrintAPIStart;
import com.xuexin.xcloud.print.entity.util.StringUtils;
import com.xuexin.xcloud.print.entity.util.XuexinConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

/**
 * Created by Administrator on 2017/7/6.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PrintAPIStart.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PrintCodeControllerTest {
    private int port = 10515;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "");
    }

    @Test
    public void updPrintCodeStatusByPrintCode() {
        String printcode = "12345";
        Integer status = 0;

        StringBuffer reqstr = new StringBuffer();
        reqstr.append("printcode=");
        reqstr.append(printcode);
        reqstr.append("&");
        reqstr.append("status=");
        reqstr.append(status);
        reqstr.append("&");

        StringBuffer valiStr = new StringBuffer();
        valiStr.append("printcode=");
        valiStr.append(printcode);
        valiStr.append("&");
        valiStr.append("status=");
        valiStr.append(status);
        valiStr.append("&");
        valiStr.append(XuexinConstants.XUEXIN_MD5_SIGN);
        String sign = StringUtils.getMD5Str(valiStr.toString());
        reqstr.append("sign=");
        reqstr.append(sign);
        template.put(base.toString() + "/printcode/edit/{printcode}?status="+status+"&sign="+sign,null,printcode);
    }
}



参考资料:

猜你喜欢

转载自blog.csdn.net/long290046464/article/details/76928778