正在使用Spring MVC创建Restful Web服务...
下面是我的pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>MyApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
web-inf/mvc-dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
<import resource="classpath:database_db.xml" />
<context:component-scan base-package="com.myapp.rest" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
src/main/resources/database_db.xml:
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="dataSourceDB" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost/mydatabase?zeroDateTimeBehavior=convertToNull</value></property>
<property name="username"><value>root</value></property>
<property name="password"><value></value></property>
</bean>
</beans>
@Controller
@RequestMapping("/v2")
public class UserController {
private final UserDAO dao;
@Autowired
public UserController(UserDAO dao) {
this.dao = dao;
}
@RequestMapping(value = "users/appId", method = RequestMethod.GET)
public @ResponseBody Object getUserDetails(@PathVariable String appId) {
Object response = null;
response = dao.getUser(appId);
return response;
}
}
@Repository public class UserDAO{
private JdbcTemplate jdbcTemplate;
@Autowired
public UserDAO(@Qualifier("dataSourceDB") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
// Various get and finder methods
}
SRC/Test/Java:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:**/mvc-dispatcher-servlet.xml")
@WebAppConfiguration
public class UserControllerTest {
@Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
@InjectMocks
private UserController userController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
public void appUser() throws Exception {
String appId = "1234FD57";
mockMvc.perform(get("/v2/users/{appId}", appId)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
}
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.myapp.rest.controllers.UserControllerTest
MockHttpServletRequest:
HTTP Method = GET
Request URI = /v2/users/1234FD57
Parameters = {}
Headers = {Accept=[application/json]}
Handler:
Type = com.myapp.rest.controllers.UserController
Method = public java.lang.Object com.myapp.rest.controllers.UserController.getUserDetails(java.lang.String)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.751 sec
mockMvc.perform(get("/v2/users/{appId}",appId)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$[1].userId", is("1234FD57")));
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.766 sec <<< FAILURE!
user(com.myapp.rest.controllers.UserControllerTest) Time elapsed: 0.157 sec <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.myapp.rest.controllers.UserControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.myapp.rest.controllers.UserController
com.myapp.rest.controllers.UserControllerTest.userController; nested exception is org.springframework.beans.factory
NoSuchBeanDefinitionException: No qualifying bean of type [com.myapp.rest.controllers.UserController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.mockito.InjectMocks(), @org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties
这就像在print()语句中没有显示“body”没有JSON一样...我真的很接近了,有人知道我在干什么吗?
由于您使用的是Spring 4.0.3,因此必须使用旧的jsonpath 0.9.1,请参阅https://jira.Spring.io/browse/spr-12299
我试图测试我的一个控制器,它返回给我一个get方法上的对象列表,以填充我页面上的下拉列表。 我试图使用MockMvc和Hamcrest编写一个JUnit测试来测试相同的内容。 我想比较对象列表,并测试它是否失败。 这就是我获取模型属性的方式: 提前谢了。
我试图使用spring和mockito对rest控制器进行单元测试。这是我的主控制器方法。 这是我的JUnit测试: 在输出响应中,测试失败,因为它得到404错误,但它预期成功代码为200。我相信我已经正确设置了独立配置,我会做错什么。为什么URI没有正确映射到方法?请注意,对于来自应用程序前端的相同URI,它工作正常。以下是我使用Postman工具为chrome测试的正确200响应的完整URI:
我需要jUnit测试的帮助,我的结果是json文件,我需要测试该文件的长度,问题是在jsonPath函数中没有这样的方法。 这里是我的测试方法,预期长度是7。如有任何帮助,我将不胜感激,谢谢
我对junit mockito非常陌生,并尝试使用mockito编写junit测试用例。 这是我的方法,我必须为此编写一个jUnit。 ChefService和ChefApi传递的方法参数来自第三方api 这里是呼叫chefService。listCookbookVersions()将返回CookBookVersion类类型的迭代器,如
我正在使用Mockito编写一个JUnit测试用例,并得到一个NullPointerException。 在我的代码中是这样的:
null null null 更新2015-06-12:Mockito 1.10.19和2.0.13-beta仍然使用Hamcrest 1.1