java - 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”
解决方案
推荐阅读
- python - DatePicker 使用 ModelForm 不可见 - 脆
- java - 条件 trowing 错误以及如何在此处使用而不会出现任何错误
- azure - K8s Cluster over Azure 使用 Kubeadm + Autoscaling 使用 VMSS
- javascript - 我正在尝试使用“Rick and Morty”REST API 在我的屏幕上呈现名称,但没有任何文字呈现,而且我的状态没有更新
- vue.js - 在 vue 中使用 url-loader 获取特定目录中的图像
- pandas - 熊猫每行获得上下栅栏
- variables - 在 Azure Pipeline 任务失败中设置变量
- java - 在 weblogic 12c 中编译 JSP 失败。类方法未定义
- android - AndroidX 迁移 - androidx.legacy:legacy-support-v4 或 androidx.appcompat:appcompat
- react-native - 使用带有样式组件的 react i18next