jeudi 31 octobre 2019

Test rest api with parameter

I am testing my 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));
    }
}

The test is...

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

However, I am keep getting...

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)
...

This is not a duplicate question as I have tried the other solutions like $.[0].fundraiserName but still no success. Any other code that is needed to solve the problem? Any advice to get this to work? Is there a way to see the contents of the JSON and check the output or do I need some kind of JSON mapper? Or is the problem to do with the charity ID?

Also I was running code test coverage with Jacoco, and it says I haven't covered this line... return ResponseEntity.ok(sponsorService.findTopFiveSponsors(charityId)); Can my current test incorporate this?

Aucun commentaire:

Enregistrer un commentaire