gpt4 book ai didi

java - 使用 HTTP GET 测试端点

转载 作者:行者123 更新时间:2023-11-28 21:20:50 26 4
gpt4 key购买 nike

如果响应和 HTTP 代码正确,我想测试端点。 Controller 方法如下所示:

@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 出现空指针异常。即使我尝试 @Autowire 它而不是实例化它也是一样的。我想从 mongo 数据库中获取一个规则对象的整个方法是错误的,但是将一个对象本地放在我的数据库中并通过他的 id 获取这个对象会更糟,因为这些测试不会在我的计算机上运行。

如果我尝试 Autowiring 我的服务,这是个异常(exception)

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)

最佳答案

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

@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);
}

}

关于java - 使用 HTTP GET 测试端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52161306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com