[英]Test rest api with parameter
我正在測試我的 REST API ...
@RestController
@RequestMapping(path = "/api")
public class SponsorAPI {
private SponsorService sponsorService;
@Autowired
public SponsorAPI(SponsorService sponsorService) {
this.sponsorService = sponsorService;
}
@GetMapping(path = "/findTopFiveSponsors")
public ResponseEntity<?> get(@Param("charityId") Long charityId) {
return ResponseEntity.ok(sponsorService.findTopFiveSponsors(charityId));
}
}
測試是...
@RunWith(SpringRunner.class)
@WebMvcTest(SponsorAPI.class)
public class SponsorAPITest {
@Autowired
private MockMvc mockMvc;
@MockBean
SponsorService sponsorService;
@MockBean
CharityService charityService;
@Test
public void shouldReturnTheTopFiveSponsors() throws Exception {
Charity nspcc = new Charity(1L,
"12345678",
"National Society for the Prevention of Cruelty to Children",
"Kids charity",
"nspcc",
"NSPCC",
true);
given(charityService.findById(1L)).willReturn(Optional.of(nspcc));
Sponsor sponsor1 = new Sponsor(2L,
"Foo Bar",
nspcc,
"Running a marathon",
"To help raise funds",
LocalDateTime.now(),
LocalDateTime.now(),
LocalDateTime.now().plusMonths(6),
"foo-bar");
// List<Sponsor> sponsors = new ArrayList<>();
// sponsors.add(sponsor1);
// given(sponsorService.findById(2L)).willReturn(Optional.of(sponsor1));
mockMvc.perform(get("/api/findTopFiveSponsors").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.fundraiserName", is("Foo Bar")));
}
}
然而,我不斷...
java.lang.AssertionError: No value at JSON path "$.fundraiserName"
at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:295)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:72)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at com.nsa.charitystarter.controllers.api.SponsorAPITest.shouldReturnTheTopFiveSponsors(SponsorAPITest.java:70)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['fundraiserName'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:71)
...
這不是一個重復的問題,因為我嘗試了其他解決方案,例如$.[0].fundraiserName
但仍然沒有成功。 解決問題所需的任何其他代碼? 有什么建議可以讓它工作嗎? 有沒有辦法查看 JSON 的內容並檢查 output 還是我需要某種 JSON 映射器? 還是慈善ID的問題?
我還在用 Jacoco 運行代碼測試覆蓋率,它說我沒有覆蓋這一行... return ResponseEntity.ok(sponsorService.findTopFiveSponsors(charityId));
我目前的測試可以包含這個嗎?
讓我假設您的代碼如下所示:
@Component
public class SponsorService {
List<Sponsor> list=new ArrayList<>();
@PostConstruct
public void init() {
list.add(new Sponsor(1L, "name1"));
list.add(new Sponsor(2L, "name2"));
list.add(new Sponsor(3L, "name3"));
}
public Optional<Sponsor> findTopFiveSponsors(Long charityId) {
return list.stream().filter(el-> el.getId().equals(charityId)).findAny();
}
}
class Sponsor{
private Long id;
private String fundraiserName;
public Sponsor() {
super();
}
public Sponsor(Long id, String fundraiserName) {
super();
this.id = id;
this.fundraiserName = fundraiserName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFundraiserName() {
return fundraiserName;
}
public void setFundraiserName(String fundraiserName) {
this.fundraiserName = fundraiserName;
}
}
主class:
@SpringBootApplication
@ComponentScan(basePackageClasses=Config.class)
public class ExampleH23Application {
public static void main(String[] args) {
SpringApplication.run(ExampleH23Application.class, args);
}
}
配置 class:
@Configuration
@ComponentScan("package.service")
public class Config {
}
Controller:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/api")
public class SponsorController {
private SponsorService sponsorService;
public SponsorController(SponsorService sponsorService) {
this.sponsorService = sponsorService;
}
@GetMapping(path = "/findTopFiveSponsors1/{charityId}")
public ResponseEntity<?> get1(@PathVariable("charityId") Long charityId) {
return tomato(charityId);
}
@GetMapping(path = "/findTopFiveSponsors2")
public ResponseEntity<?> get2(@RequestParam("charityId") Long charityId) {
return tomato(charityId);
}
private ResponseEntity<?> tomato(Long charityId) {
Optional<Sponsor> item = sponsorService.findTopFiveSponsors(charityId);
if (item.isPresent()) {
return ResponseEntity.ok(item.get());
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
Controller 測試:
@ExtendWith(SpringExtension.class) // if you use junit 4 you replace this by @RunWith(SpringRunner.class)
@WebMvcTest(SponsorController.class)
public class SponsorControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void test1() throws Exception {
mockMvc
.perform(get("/api/findTopFiveSponsors1/{charityId}",1)
.param("charityId", "1"))
.andDo(print())
.andExpect(status().is(HttpStatus.OK.value()))
.andExpect(jsonPath("$.fundraiserName", is("name1")));
}
@Test
public void test2() throws Exception {
mockMvc
.perform(get("/api/findTopFiveSponsors2")
.param("charityId", "3"))
.andDo(print())
.andExpect(status().is(HttpStatus.OK.value()))
.andExpect(jsonPath("$.fundraiserName", is("name3")));
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>example-H2-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>example-H2-3</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
所有測試都是綠色的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.