我对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”