Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 带json的SpringRESTJUnitPost_Java_Json_Spring_Rest_Junit - Fatal编程技术网

Java 带json的SpringRESTJUnitPost

Java 带json的SpringRESTJUnitPost,java,json,spring,rest,junit,Java,Json,Spring,Rest,Junit,我正试图与project合作,为SpringRESTWebService创建junit测试。get方法可以很好地实现这一点,但它确实可以使用post json作为输入。下面是get方法的代码。如果有人帮助rest post json junit测试,将不胜感激 @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(位置=(“/spring/application config.xml”

我正试图与project合作,为SpringRESTWebService创建junit测试。get方法可以很好地实现这一点,但它确实可以使用post json作为输入。下面是get方法的代码。如果有人帮助rest post json junit测试,将不胜感激

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(位置=(“/spring/application config.xml”))
公共类LoginServiceFacadeTestImpl扩展了AbstractTest{
@自动连线
私有WebApplicationContext wac;
私有MockMvc-MockMvc;
@以前
公共作废设置(){
this.mockMvc=MockMvcBuilders.webAppContextSetup(this.wac.build();
}
@试验
public void testSearchProductByNameFound()引发异常{
字符串关键字=”;
this.mockMvc.perform(get(“/perlogin”)
.param(“q”,关键字)
.accept(MediaType.APPLICATION_JSON))
.andExpect(状态().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath($name”).value(关键字));
}
}
但我得到的错误如下

经过的时间:5.477秒

@ContextConfiguration(locations=("/spring/application-config.xml"))
参考您所展示的XML配置,没有注册
@Controller
bean,因此没有任何东西可以处理任何请求

您的
@ContextConfiguration
可能正在加载
DispatcherServlet
使用的
DispatcherServlet.xml
文件。该上下文配置文件应包含

<mvc:annotation-driven /> 


将任何找到的
@Controller
bean注册为处理程序。

因此组件扫描程序将拾取您的控制器

看看这是否适合您:

我的方法使用Jackson对对象进行JSon编码,并直接用JSon发布Rest服务。控制器有一个实用程序,用于从HttpServletRequest检索包含Json的主体。我知道还有其他方法可以做到这一点

我的测试

package com.myproject.test;

import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.myproject.domain.Element;
import com.myproject.model.DbBrokerModel;
import com.myproject.rest.PostJsonRestTest;

// Not sure if you need any of this for your test so just delete it if you don't 
@Configuration
@PropertySource(value={
        "classpath:usermgmt.properties",
        "classpath:ldap.properties",
        "classpath:jdbc.properties",
        "classpath:email.properties"
})
@ContextConfiguration(locations = {
        "file:src/main/webapp/WEB-INF/spring-config.xml",
        "file:src/main/webapp/WEB-INF/conf/applicationContext-email.xml",
        "file:src/main/webapp/WEB-INF/conf/applicationContext-jdbc.xml"

})
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PostJsonRestTest {


    private static final Logger log = Logger.getLogger(PostJsonRestTest.class);


    @Autowired
    private WebApplicationContext ctx;
    MockMvc mockMvc;

    @InjectMocks
    private PostJsonRest jsonRest;


    // TODO @Inject or @Autowired anything you may need 


    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build();
    }

    @After
    public void tearDown() throws Exception {
    }


    /**
     * <b>triggerJsonPostTest</b><br/>
     * Explain what you are doing
     * 
     */
    @Test
    public void triggerJsonPostTest() {


        //Set up the model to be converted to Json
        TestModel requestModel = new TestModel();


        // Build the Model object and stuff them with test data
        List<Element> elements = new ArrayList<Element>();
        requestModel.setElementId("123");
        requestModel.setElementType("change");
        requestModel.setElementsAffected(3);
        requestModel.setChanges(elements);



        try {
            //Convert the Test Model To JSon
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] requestJson =  objectMapper.writeValueAsBytes(requestModel);

            //Call your rest contoller 
            MvcResult result = this.mockMvc.perform(post("/test/receive-json")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(requestJson))
                    .andDo(print())
                    .andExpect(status().isOk())             
                    .andReturn();
            //TODO Wrtie a bunch of validation for the return OBJECT
            //TODO: Remember to test for positive and negative results in seperate @Test's 


        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

}
package com.myproject.test;
导入静态org.junit.Assert.fail;
导入静态org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
导入静态org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
导入静态org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.log4j.Logger;
导入org.codehaus.jackson.map.ObjectMapper;
导入org.junit.After;
导入org.junit.Before;
导入org.junit.Test;
导入org.junit.runner.RunWith;
导入org.mockito.InjectMocks;
导入org.mockito.MockitoAnnotations;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.beans.factory.annotation.Qualifier;
导入org.springframework.context.annotation.Configuration;
导入org.springframework.context.annotation.PropertySource;
导入org.springframework.http.MediaType;
导入org.springframework.test.context.ContextConfiguration;
导入org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
导入org.springframework.test.context.web.WebAppConfiguration;
导入org.springframework.test.web.servlet.MockMvc;
导入org.springframework.test.web.servlet.MvcResult;
导入org.springframework.test.web.servlet.setup.MockMvcBuilders;
导入org.springframework.web.context.WebApplicationContext;
导入com.myproject.domain.Element;
导入com.myproject.model.DbBrokerModel;
导入com.myproject.rest.PostJsonRestTest;
//不确定测试是否需要这些,如果不需要,请删除它
@配置
@PropertySource(值={
“类路径:usermgmt.properties”,
“类路径:ldap.properties”,
“classpath:jdbc.properties”,
“类路径:email.properties”
})
@上下文配置(位置={
“文件:src/main/webapp/WEB-INF/spring config.xml”,
“文件:src/main/webapp/WEB-INF/conf/applicationContext email.xml”,
“文件:src/main/webapp/WEB-INF/conf/applicationContext jdbc.xml”
})
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
公共类PostJsonRestTest{
私有静态最终记录器log=Logger.getLogger(PostJsonRestTest.class);
@自动连线
私有WebApplicationContext ctx;
MockMvc-MockMvc;
@注射模拟
私有PostJsonRest-jsonRest;
//TODO@Inject或@Autowired您可能需要的任何内容
@以前
public void setUp()引发异常{
initMocks(this);
this.mockMvc=MockMvcBuilders.webAppContextSetup(this.ctx.build();
}
@之后
public void tearDown()引发异常{
}
/**
*triggerJsonPostTest
*解释你在做什么 * */ @试验 公共无效触发器JsonPostTest(){ //设置要转换为Json的模型 TestModel requestModel=新的TestModel(); //构建模型对象并用测试数据填充它们 列表元素=新的ArrayList(); requestModel.setElementId(“123”); requestModel.setElementType(“更改”); requestModel.setElementsAffected(3); requestModel.setChanges(元素); 试一试{ //将测试模型转换为JSon ObjectMapper ObjectMapper=新的ObjectMapper(); byte[]requestJson=objectMapper.writeValueAsBytes(requestModel); //打电话给你的休息控制员 MvcResult result=this.mockMvc.perform(post(“/test/receive json”) .contentType(MediaType.APPLICATION_JSON) .content(requestJson)) .andDo(print()) .andExpect(状态().isOk()) .andReturn(); //TODO为返回对象编写了一系列验证 //TODO:记住在单独的@test中测试阳性和阴性结果 }捕获(例外e){ e、 printStackTr
package com.myproject.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <b>PostJsonRest</b><br/>
 * Rest Controller Example
 * @author dhargis
 *
 *
 */
@Controller
public class PostJsonRest {

    private static final Logger log = Logger.getLogger(PostJsonRest.class);


    //TODO You may want to @Inject or @Autowire something here 

    /**
     * <b>receivePostJSon</b><br/>
     * Listens for properly formated JSon formated request of object type TestModel
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(
            value = "/trigger/receive-json", 
            method = RequestMethod.POST, 
            produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public void receivePostJSon(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String body = "";
        try{
            //See below utility class 
            body =  getBody(request);

            //TODO You may want to log something here 

        }
        catch(IOException e){

            log.warn("Error: Problems parsing incoming JSON request  ", e);

        }

        finally{


        }

        // TODO REMOVE Temporary Output to the command line before deployment
        System.out.println(body);

    }

    /**
     * <b>getBody</b><br/>
     * This little utility class will give you the body containing the JSON
     * @param request
     * @return
     * @throws IOException
     */

    private String getBody(HttpServletRequest request) throws IOException {
        String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            log.error("Error while reading the request body", ex);
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    log.error("Error while closing the reading for request body", ex);
                    throw ex;
                }
            }
        }
        body = stringBuilder.toString();
        return body;
    }

}