package com.maxbox.test;

import com.alibaba.fastjson.JSONObject;
import com.maxbox.Bean.Person;
import com.maxbox.common.FastApplicationTests;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

public class TestHelloController extends FastApplicationTests {

    @Test
    public void getHello() throws Exception {
        //--1、验证controller是否正常响应并打印返回结果
       /*mvc.perform(MockMvcRequestBuilders.get("/test/hello").param("name","1234").accept(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(MockMvcResultMatchers.status().isOk())
        .andDo(MockMvcResultHandlers.print()).andReturn();*/
        //--2、验证controller是否正常响应并判断返回文本结果是否正确
       /* mvc.perform(MockMvcRequestBuilders.get("/test/getTexthello").
                param("name", "1234").accept(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string(("success")));*/
        //--3、Spring Mock的方式发送post请求，参数正确设置到请求方法体中
        Person person = new Person(1, "张三");
        mvc.perform(MockMvcRequestBuilders.post("/test/saveHello").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).
                content(JSONObject.toJSONString(person))).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
        //--4、restful请求方式
        String apiUrl = "/test/hello/123";
        mvc.perform(MockMvcRequestBuilders.get(apiUrl).accept(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print()).andReturn();
        //--5、验证controller是否正常响应并判断返回结果code是否正确
        MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/test/hello").
                param("name", "world").accept(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        JSONObject jsonObject = JSONObject.parseObject(result.getResponse().getContentAsString());
//      System.out.println(reslut.getResponse().getContentAsString());
        Assert.assertSame("验证状态码错误", 123, jsonObject.getIntValue("code"));
    }

}
