【发布时间】:2025-12-09 18:15:02
【问题描述】:
我是 junit 的新手。想为以下功能编写测试用例。但我对如何开始感到困惑。我写了一些测试用例,但没有成功。希望有人能帮助我。
@Controller
@RequestMapping("/")
public class TodoController {
public List<Todo> allTODO;
//USER CREATION
@RequestMapping(method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
Integer createUser(User user) {
HibernateUtils.BuildSessionFactory();
Integer id= (Integer)session.save(user);
HibernateUtils.commit();
return id;
}
//INSERTING A TODO FOR A PARTICULAR USER
@RequestMapping(value = "/{uid}/todos", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Todo getAllTodo(@PathVariable("uid") int uid, @RequestBody Todo todo) {
//Todo todo1= new Todo(todo.getText(), new User(uid));
todo.setUser(new User(uid));
HibernateUtils.BuildSessionFactory();
session.save(todo);
HibernateUtils.commit();
return todo;
}
//FETCHING USER TODOS FROM DATABASE
@RequestMapping(value = "/{uid}/todos", method = RequestMethod.GET,
consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String getTodoForUser(@PathVariable("uid") int uid) {
HibernateUtils.BuildSessionFactory();
Query queryResult = session.createQuery("from Todo");
allTODO = queryResult.list();
HibernateUtils.commit();
List<Todo> usersTodos= getTodoWithUid(uid);
Iterator<Todo> i= usersTodos.iterator();
String todos="";
while(i.hasNext())
todos+= i.next().toString()+"\n";
return todos;
}
}
我的 TodoControllerTest 方法
@RunWith(MockitoJUnitRunner.class)
public class TodoControllerTest {
private MockMvc mockMvc=null;
@InjectMocks
private TodoController todoController;
@Before
public void setup() {
// mockMvc=new MockMvc();
// process mock annotations
MockitoAnnotations.initMocks(this);
// setup spring test in standalone mode
mockMvc = MockMvcBuilders.standaloneSetup(todoController).build();
}
@Test
public void testCreateUserPostRequest() throws Exception {
this.mockMvc.perform(post("/users")
.param("uid", "1"))
.andExpect(status().isOk());
}
@Test
public void testGetTodoForUser() throws Exception {
this.mockMvc.perform(get("/users/{uid}/todos"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].text", is("hi")))
.andExpect(jsonPath("$[0].user", is(1)));
verify(todoController, times(1)).getAllTodo((Integer) Mockito.any(), (Todo) Mockito.any());
verifyNoMoreInteractions(todoController);
}
@Test
public void testGetAllTodoPostRequest() throws Exception {
this.mockMvc.perform(post("/users/{uid}/todos")
.param("id", "1")
.param("text","hey")
.param("user","1"))
.andExpect(status().isOk());
}
}
当我运行这个测试时,我得到以下错误:
sun.misc.ServiceConfigurationError: java.nio.charset.spi.CharsetProvider: Provider
com.intellij.lang.properties.charset.Native2AsciiCharsetProvider not found
at sun.misc.Service.fail(Service.java:129)
at sun.misc.Service.access$000(Service.java:111)
at sun.misc.Service$LazyIterator.next(Service.java:273)
at java.nio.charset.Charset$1.getNext(Charset.java:319)
at java.nio.charset.Charset$1.hasNext(Charset.java:332)
at java.nio.charset.Charset$4.run(Charset.java:551)
at java.security.AccessController.doPrivileged(Native Method)
at java.nio.charset.Charset.availableCharsets(Charset.java:546)
at org.springframework.http.converter.StringHttpMessageConverter.<init>(StringHttpMessageConverter.java:68)
at org.springframework.http.converter.StringHttpMessageConverter.<init>(StringHttpMessageConverter.java:58)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.<init>(RequestMappingHandlerAdapter.java:178)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerAdapter(WebMvcConfigurationSupport.java:362)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.registerMvcSingletons(StandaloneMockMvcBuilder.java:285)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.initWebAppContext(StandaloneMockMvcBuilder.java:272)
at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.build(DefaultMockMvcBuilder.java:186)
at com.persistent.todo.TodoControllerTest.setup(TodoControllerTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:202)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
我的 pom 文件包括:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-compiler</artifactId>
<version>0.6.350</version>
</dependency>
【问题讨论】:
-
还有一个“不工作”!!!
-
你说的没有成功是什么意思?
-
您不希望
public List<Todo> allTODO;作为控制器上的字段! (因为这个字段被每个请求共享)
标签: java json hibernate spring-mvc junit