基于SpringBoot
package share.procon.modular.project.controller
import com.alibaba.fastjson.JSONObject
import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
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.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.ResultActions
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EntMajorControllerTest {
@Autowired
private MockMvc mockMvc
private String Authorization = ""
private JSONObject jsonObject = new JSONObject()
@Before
public void getAuthorization() throws IOException {
getToken()
}
@Test
@Transactional
public void addEntItem() throws Exception {
jsonObject.put("entMname","软件工程")
jsonObject.put("entMcode","12345")
ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/entMajor/addEntMajor")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", Authorization)
//Rest风格提交
.content(jsonObject.toString().getBytes())
)
resultActions.andExpect(MockMvcResultMatchers.status().isOk())
resultActions.andDo(MockMvcResultHandlers.print())
}
private void getToken() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault()
CloseableHttpResponse httpResponse = null
HttpPost httpPost = new HttpPost("http://127.0.0.1:8000/authAction/shareAuth")
//表单方式
//json格式
JSONObject jsonParam = new JSONObject()
jsonParam.put("userName", "admin@test")
jsonParam.put("password", "MTIzNDU2")
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8")
entity.setContentEncoding("UTF-8")
entity.setContentType("application/json")
httpPost.setEntity(entity)
httpResponse = httpClient.execute(httpPost)
HttpEntity httpEntity = httpResponse.getEntity()
byte[] b = EntityUtils.toByteArray(httpEntity)
JSONObject jsonObject = JSONObject.parseObject(b, JSONObject.class)
Authorization = jsonObject.getJSONObject("data").getString("token")
System.out.println("获取到的token-----------------------:" + Authorization)
httpClient.close()
}
}