【问题标题】:How do I change this Spring Test Framework Test to work with a JSON return?如何更改此 Spring Test Framework Test 以使用 JSON 返回?
【发布时间】:2013-06-11 13:45:52
【问题描述】:

我正在尝试更改以下 Spring Test Framework 以测试以下 json 返回:

{"user":"John ","name":"JohnSmith"}

这是我的测试代码,我只是不知道如何更改它以检查 JSON 和 JSON 中的值。如果有人能告诉我要改变什么,那就太好了。谢谢

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebMVCConfig.class})
@WebAppConfiguration
public class TestHelloWorldWeb
{
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

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

    @Test
    public void getFoo() throws Exception
    {
        this.mockMvc.perform(get("/ask")
                .accept(MediaType.TEXT_HTML))
                .andExpect(status().isOk())
                .andExpect(view().name("helloworld"))
                .andExpect(MockMvcResultMatchers.model().attribute("user", "JohnSmith"))
        ;


    }
}

【问题讨论】:

    标签: spring spring-mvc spring-test-mvc


    【解决方案1】:
    .andExpect(jsonPath("$.user").value("john"));
    

    有依赖关系:

    <dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>0.8.1</version>
    </dependency>
    

    还有一个像这样的静态导入

    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
    

    添加静态方法...

    【讨论】:

    • 什么是jsonPath?我的代码不会构建!它不知道jsonpath是什么
    • @user2428795 “什么都没有”是什么意思?您将收到导入错误,因为 jsonpath 不可用。或者它将编译并运行执行断言
    • jsonpath 不可用
    • 你当时没有添加依赖,或者没有正确导入
    • 你没有,否则你不会得到“它不可用”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    相关资源
    最近更新 更多