簡體   English   中英

JSON路徑“ $ .name”處沒有值,例外:使用Mockmvc和Spring-boot時json不能為null或為空

[英]No value at JSON path “$.name”, exception: json can not be null or empty, Using Mockmvc and Spring-boot

本着學習使用Spring Mock-Mvc和/或Mockito進行Spring-boot的精神,我構建了一個小型API,當我學習更多內容時,有可能會變得復雜。

主題是“冰與火之歌”或“權力的游戲”。 到目前為止,我只有一個軟件包,可以在向“ / Westeros”發送請求時添加,刪除和獲得不同的王國。 每個王國現在只需要一個name屬性。

我正在使用的數據庫是Neo4J。

我將代碼上傳到github,這是鏈接https://github.com/darwin757/IceAndFire

問題:在Porblem是在方法addKingdomTestupdateKingdomTestKingdomControllerTest

    @Test
public void addKingdomTest() throws Exception {

    mockMvc.perform(post("/Westeros").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\"name\":\"Dorne\"}")
            .accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isCreated()).andReturn();

    //This part of the test is not working
    mockMvc.perform(get("/Westeros/Dorne").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("Dorne"));

}

@Test
public void updateKingdomTest() throws Exception {

    mockMvc.perform(post("/Westeros").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\"name\":\"Dorne\"}")
            .accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isCreated());

    mockMvc.perform(put("/Westeros/Dorne").contentType(MediaType.APPLICATION_JSON_UTF8)
            .content("{\"name\":\"theReach\"}").accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk());

    //This Part of the test is not working
    mockMvc.perform(get("/Westeros/Dorne").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("the Reach"));

}

如您所見,當我要求API創建新的王國時,它返回201 isCreated或200 isOK,但是當我發送get請求時,我得到的是“ JSON路徑異常無值”

java.lang.AssertionError: No value at JSON path "$.name", exception: json can not be null or empty
at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:245)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:99)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers$2.match(JsonPathResultMatchers.java:100)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.example.Westeros.Kingdoms.KingdomControllerTest.addKingdomTest(KingdomControllerTest.java:95)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

我總體上對Spring還是很陌生,但是我沒有在Spring Mock-Mvc或Mockito上找到適當的指南。 我不知道這是什么錯誤,是我的語法還是我的API? 任何幫助,將不勝感激。

這是整個班級:

package com.example.Westeros.Kingdoms;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.stubbing.OngoingStubbing;
import org.springframework.beans.factory.annotation.Autowired;
import 
org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.mockito.Mockito.when;
import static org.junit.Assert.*;
import static org.mockito.Mockito.any;

import static 
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static 
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static 
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static 
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static 
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static 
org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static 
org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static 
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;

//TODO Major refactor required to clean up this class and consider the 
testing strategy 
@RunWith(SpringRunner.class)
@SpringBootTest
public class KingdomControllerTest {

@Autowired
private WebApplicationContext context;

private MockMvc mockMvc;

@MockBean
private KingdomService kingdomServiceMock;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}

@Test
public void getAllKingdomsTest() throws Exception {

    List<Kingdom> kingdoms = setUpAListOfKingdoms();

    when(kingdomServiceMock.getAllKingdoms()).thenReturn(kingdoms);

    mockMvc.perform(get("/Westeros").accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$[0].name").value("TheNorth"))
            .andExpect(jsonPath("$[1].name").value("TheRiverlands"));
}


@Test
public void getKingdomTest() throws Exception {

    Kingdom theNorth = setUpAKingdom("TheNorth");
    kingdomServiceMock.addKingdom(theNorth);

    when(kingdomServiceMock.getKingdom("TheNorth")).thenReturn(theNorth);

    mockMvc.perform(get("/Westeros/TheNorth")).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.name").value("TheNorth"));
}

// FIXME This test is returning 201 isCreated,
// but if I perform a get after I get an assertion exception that the variable
// name is empty.
@Test
public void addKingdomTest() throws Exception {

    mockMvc.perform(post("/Westeros").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\"name\":\"Dorne\"}")
            .accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isCreated()).andReturn();

    //This part of the test is not working
    mockMvc.perform(get("/Westeros/Dorne").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("Dorne"));

}

@Test
public void updateKingdomTest() throws Exception {

    mockMvc.perform(post("/Westeros").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\"name\":\"Dorne\"}")
            .accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isCreated());

    mockMvc.perform(put("/Westeros/Dorne").contentType(MediaType.APPLICATION_JSON_UTF8)
            .content("{\"name\":\"theReach\"}").accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk());

    //This Part of the test is not working
    mockMvc.perform(get("/Westeros/Dorne").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("the Reach"));

}

@Test
public void deleteKingdomTest() throws Exception {

    mockMvc.perform(post("/Westeros").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\"name\":\"theVale\"}")
            .accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isCreated());

    mockMvc.perform(delete("Westeros/theVale").contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isNotFound());

}

// FIXME refer to the KingdomController class, the method should be moved to
// another class more suited to it's purpose
@Test
public void deleteAlltest() {
}

private List<Kingdom> setUpAListOfKingdoms() {

    Kingdom theNorth = setUpAKingdom("TheNorth");
    Kingdom theRiverlands = setUpAKingdom("TheRiverlands");

    List<Kingdom> kingdoms = new ArrayList<Kingdom>();

    kingdoms.add(theNorth);
    kingdoms.add(theRiverlands);

    // FIXME wrong place for this code but I can't find another
    kingdomServiceMock.addKingdom(theNorth);
    kingdomServiceMock.addKingdom(theRiverlands);

    return kingdoms;

}

private Kingdom setUpAKingdom(String name) {

    Kingdom kingdom = new Kingdom(name);
    return kingdom;
}

}

先感謝您。

好的,我檢查了您的github,問題是您在模擬KingdomService:

@MockBean
private KingdomService kingdomServiceMock;

但是在這些失敗的測試中,您並未斷言所調用的模擬方法的任何行為。 模擬類的默認響應是返回null,因此這里的KingdomService.getKingdom(name)方法始終返回null:

@RequestMapping("/Westeros/{name}")
    public Kingdom getKingdom(@PathVariable String name) {
        return kingdomService.getKingdom(name);
}

您可能想要做更多的集成測試,在這種情況下,我會說您不想模擬該服務。

因此,在當前正在運行的獲取測試中,而不是設置模擬行為,您應該自動連接存儲庫並實際添加要測試的王國,例如:

@Autowired
KingdomRepository kingdomRepository;

@Test
@Transactional
    public void getAllKingdomsTest() throws Exception {

        List<Kingdom> kingdoms = setUpAListOfKingdoms();

        kingdomRepository.saveAll(kingdoms);
        kingdomRepository.flush();

        mockMvc.perform(get("/Westeros").accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$[0].name").value("TheNorth"))
                .andExpect(jsonPath("$[1].name").value("TheRiverlands"));
    }

@Transactional批注可確保您與數據庫的交互在每次測試結束時回滾。

編輯:您還應該確保您的存儲庫正在實現JpaRepository而不是PagingAndSortingRepository。 這樣,您可以在存儲庫上調用.flush()方法,以確保對數據庫的所有未完成的更改都立即刷新到該數據庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM