使用HTTP GET测试端点

时间:2018-09-04 07:46:35

标签: 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() 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);

}

我的ruleService出现nullpointer异常。即使我尝试@Autowire并且不实例化它也是一样的。我猜想从mongo数据库中获取一个规则对象的整个方法是错误的,但是将一个对象放在本地数据库中并通过其id获取该对象会更加糟糕,因为这些测试无法在我的计算机上运行。

这是例外,如果我尝试自动连接服务

java.lang.NullPointerException
at com.%%%%.^^^^.controller.v2.test.RuleControllerTest.loadOneRule(RuleControllerTest.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:42)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.forEach(Unknown Source)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:83)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:74)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

1 个答案:

答案 0 :(得分:1)

您不需要使用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);
    }

}