首页 > 解决方案 > Junit 测试用例失败:- org.junit.ComparisonFailure

问题描述

我是junit和mockito的新手。在这个特定的示例中,我正在尝试测试我的 HelloController 方法。

@RestController
public class HelloController {



    @RequestMapping("/hello-world")
    public String helloWorld() {
        return "Hello World";
    }

}

我希望这种测试方法能够成功,但不幸的是它失败了。有人可以解释为什么这个测试失败了吗?

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
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.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;


@RunWith(SpringRunner.class)
@WebMvcTest(value=HelloWorldControllerTest.class)
public class HelloWorldControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @Test
    public void helloWorld_basic() throws Exception {

        RequestBuilder request = MockMvcRequestBuilders
                .get("/hello-world")
                .accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(request).andReturn();
        assertEquals("Hello World",result.getResponse().getContentAsString());

    }

}

故障跟踪说: -

org.junit.ComparisonFailure: expected:<[Hello World]> but was:<[]>

但我的控制器方法显然返回“Hello World”

标签: javajunitmockito

解决方案


推荐阅读