Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.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 使用HTTP GET测试端点_Java_Spring_Mongodb_Testing - Fatal编程技术网

Java 使用HTTP GET测试端点

Java 使用HTTP GET测试端点,java,spring,mongodb,testing,Java,Spring,Mongodb,Testing,我想测试端点的响应和HTTP代码是否正确。控制器方法如下所示: @CrossOrigin @RequestMapping(method = RequestMethod.GET, value = "/{ruleId}") public Rule loadOneRule(@PathVariable String ruleId) { return rulesService.loadOneRule(ruleId); } 试验方法为: @Test public void loadOneRule(

我想测试端点的响应和HTTP代码是否正确。控制器方法如下所示:

@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/{ruleId}")
public Rule loadOneRule(@PathVariable String ruleId) {
    return rulesService.loadOneRule(ruleId);
}
试验方法为:

@Test
public void loadOneRule() throws IOException, URISyntaxException { 
    NodeDTO nodeDto = new NodeDTO();
    HashMap<String, NodeDTO> nodes = new HashMap<>();
    nodes.put("foo", nodeDto);

    Rule rule = new Rule("my rule", nodes);
    RuleService ruleService = new RuleService();
    rule = ruleService.saveRule(rule);
    String id = rule.getId().toString();

    String target = "http://localhost:8090" + "/v2/rules/" + id; 

    URI uri = new URI(target);
    HttpGet httpGet = new HttpGet(uri.toASCIIString());

    HttpResponse response = httpClient.execute(httpGet);
    int HTTPcode = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    String json = EntityUtils.toString(entity);

    ObjectMapper objectMapper = new ObjectMapper();
    Rule targetRule = objectMapper.readValue(json, Rule.class);

    boolean correctStatus = HTTPcode >= 200 && HTTPcode <= 300 ? true : false;
    boolean correctResponse = targetRule != null ? true : false;

    assertTrue(correctStatus);
    assertTrue(correctResponse);

}

您不需要使用HttpClient发出请求,而是可以使用@WebMVCTest来测试您的控制器。还有一件事,您不需要通过创建对象来指定依赖项,而需要使用@MockBean来模拟它们。在下面的代码中,您可以在@WebMvcTest注释中指定确切的控制器名称

@RunWith(SpringRunner.class)
@WebMvcTest(value = YourController.class, secure = false)
public class YourControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private StudentService rulesService;

    Rule mockRule = new Rule();


    @Test
    public void testLoadOneRule() throws Exception {

        Mockito.when(
                rulesService.loadOneRule(Mockito.anyString(),
                        Mockito.anyString())).thenReturn(mockCourse);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/{ruleId}","rule1")

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());
        String expected = "{id:rule1,name:'RuleName'}";

        JSONAssert.assertEquals(expected, result.getResponse()
                .getContentAsString(), false);
    }

} 

不要创建RuleService的实例,您将需要自动连接一个实例。如果仍然有异常,请发布该异常。有没有理由不简单地使用RestTemplate或MockMvc来测试控制器?@M.Deinum他们说不模拟所有对象会更容易。我在本地运行我的项目,并成功地为HTTP GET做了3个测试,但这一个看起来更复杂,因为我必须在数据库中有对象才能获取它的mongo id,所以URL以这个字符串结尾。我确实尝试自动连接规则服务,但在同一行代码中,我遇到了与nullpointer异常相同的问题。我在哪里声明您需要模拟所有对象?发布空指针和您的实际测试用例。那么创建或自动连接规则服务将不起作用。您需要检索一条规则,该规则在您的测试不在本地的服务器上可用。否。因为您的服务是在tomcat上运行的,而不是您测试的本地服务。
@RunWith(SpringRunner.class)
@WebMvcTest(value = YourController.class, secure = false)
public class YourControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private StudentService rulesService;

    Rule mockRule = new Rule();


    @Test
    public void testLoadOneRule() throws Exception {

        Mockito.when(
                rulesService.loadOneRule(Mockito.anyString(),
                        Mockito.anyString())).thenReturn(mockCourse);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/{ruleId}","rule1")

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());
        String expected = "{id:rule1,name:'RuleName'}";

        JSONAssert.assertEquals(expected, result.getResponse()
                .getContentAsString(), false);
    }

}