Tag: spring test mvc

如何在执行junit时将参数传递给Spring MVC控制器中的post方法?

我正在对我的Spring MVC控制器方法进行unit testing。 下面是我尝试unit testing的方法,因为它在我启动服务器时工作正常。 每当我打到index页面时,它会在浏览器上显示三个文本框,我在其中键入数据并按下提交按钮,然后调用addNewServers并使用正确的值。 现在我需要对同样的事情进行unit testing: @RequestMapping(value = “/index”, method = RequestMethod.GET) public Map addNewServer() { final Map model = new LinkedHashMap(); return model; } @RequestMapping(value = “/index”, method = RequestMethod.POST) public Map addNewServers(@RequestParam String[] servers, @RequestParam String[] address, @RequestParam String[] names) { } 以下是我的junit课程: private MockMvc mockMvc; @Before public void setup() throws […]

使用Powermock测试Spring控制器

我有一个测试特定控制器的类,它工作正常 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = “classpath:config/test-applicationContext-config.xml”) @TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) public class TestAdminController { //….. } 我使用了mockito.org上的Google的Mockito库来模拟我的底层bean。 现在我的问题是:我有一些类需要被嘲笑,但他们有final方法,谷歌的mockito似乎没有解决这个问题。 我的一位同事建议使用powermock.org上的Powermock 。 但它需要使用@RunWith(PowerMockRunner.class)注释来注释测试器类。 如果我使用这个,我必须删除注释@RunWith(SpringJUnit4ClassRunner.class) ,这将给我带来问题,因为不会创建Spring测试上下文。 我怎么能避免这种情况? 建议我配置使用PowerMockRule而不是@RunWith注释 我的项目Maven依赖项如下 org.powermock powermock-mockito-release-full 1.5 pom org.powermock powermock-module-junit4-rule 1.5 test org.powermock powermock-classloading-xstream 1.5 test 现在我的class级看起来像这样(另一个控制器测试) @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = “classpath:config/test-applicationContext-config.xml”) @TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) @PrepareForTest(ADSynchronizationImpl.class) public class ThirdPartyLoginControllerTest { @Rule public […]

@WithUserDetails和spring boot 1.4 TestEntityManager问题

我有Spring Boot的TestEntityManager和@WithUserDetails注释的问题。 这是我的测试套件: public class AdvertisementAuthorizationTest extends AbstractIntegrationTest { private static final String IMPERSONATOR_EMAIL = “joe.hacker@gmail.com”; private final static String OWNER_OF_ADVERTISEMENT_EMAIL = “john.nice@gmail.com”; @Autowired private TestEntityManager testEntityManager; @Autowired private MockMvc mockMvc; private Advertisement advertisement; private UserAccount impersonator; private ObjectMapper mapper = new ObjectMapper(); @Before public void setUp() { advertisement = testEntityManager.persist(createAdvertisement(OWNER_OF_ADVERTISEMENT_EMAIL)); impersonator = testEntityManager.persist(createUserAccount(IMPERSONATOR_EMAIL)); } […]

unit testingSpring MissingServletRequestParameterException JSON响应

我在Spring引导rest控制器中有POST方法,如下所示 @RequestMapping(value=”/post/action/bookmark”, method=RequestMethod.POST) public @ResponseBody Map bookmarkPost( @RequestParam(value=”actionType”,required=true) String actionType, @RequestParam(value=”postId”,required=true) String postId, @CurrentUser User user) throws Exception{ return service.bookmarkPost(postId, actionType, user); } 现在,如果我在Postman中测试缺少参数,我会获得400个http响应和一个JSON正文: { “timestamp”: “2015-07-20”, “status”: 400, “error”: “Bad Request”, “exception”: “org.springframework.web.bind.MissingServletRequestParameterException”, “message”: “Required String parameter ‘actionType’ is not present”, “path”: “/post/action/bookmark” } 直到现在它没关系,但是当我尝试进行unit testing时,我没有得到JSON响应 @Test public void bookmarkMissingActionTypeParam() throws Exception{ // @formatter:off […]

Spring4 MVCunit testing无法编译

在Spring 3.2.5→4.0.0版本更新后尝试编译源代码时,我有一些奇怪的行为。 ApplicationControllerTest.java错误代码片段(相当于文档中的代码): import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; … @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } 错误: COMPILATION ERROR : /C:/Development/…/war/src/test/java/org/…/web/controller/ApplicationControllerTest.java:[59,61] C:\Development\…\war\src\test\java\org\…\web\controller\ApplicationControllerTest.java:59: incompatible types; inferred type argument(s) java.lang.Object do not conform to bounds of type variable(s) B found : org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder required: java.lang.Object 如果看一下MockMvcBuilders来源,可以看出差异: […]

如何使用mockMvc检查响应体中的JSON

这是我的控制器内部的方法,由@Controller注释 @RequestMapping(value = “/getServerAlertFilters/{serverName}/”, produces = “application/json; charset=utf-8”) @ResponseBody public JSONObject getServerAlertFilters(@PathVariable String serverName) { JSONObject json = new JSONObject(); List filteredAlerts = alertFilterService.getAlertFilters(serverName, “”); JSONArray jsonArray = new JSONArray(); jsonArray.addAll(filteredAlerts); json.put(SelfServiceConstants.DATA, jsonArray); return json; } 我期待{“data”:[{“useRegEx”:”false”,”hosts”:”v2v2v2″}]}作为我的json。 这是我的JUnit测试: @Test public final void testAlertFilterView() { try { MvcResult result = this.mockMvc.perform(get(“/getServerAlertFilters/v2v2v2/”).session(session) .accept(“application/json”)) .andDo(print()).andReturn(); String content = […]

java.lang.AssertionError:junit Spring MVC Controller时未设置内容类型?

我正在使用JUnit来测试我的Spring MVC控制器。 下面是我的方法,它返回一个index.jsp页面并在屏幕上显示Hello World – @RequestMapping(value = “index”, method = RequestMethod.GET) public HashMap handleRequest() { HashMap model = new HashMap(); String name = “Hello World”; model.put(“greeting”, name); return model; } 以下是我对上述方法的JUnit测试: public class ControllerTest { private MockMvc mockMvc; @Before public void setup() throws Exception { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix(“/WEB-INF/views/”); viewResolver.setSuffix(“.jsp”); this.mockMvc = standaloneSetup(new […]

Spring的MockMvc是用于unit testing还是集成测试?

Spring有两个MockMvc设置: 独立设置 WebApplicationContext设置 一般来说,MockMvc用于什么样的测试? 单位还是整合? 或两者? 我正确地说,使用独立设置(在Spring的应用程序上下文之外运行)允许您编写unit testing,并且使用WebApplicationContext设置可以编写集成测试吗?

在Spring Boot 1.4中测试安全性

我正在尝试使用SecurityConfig类中定义的自定义安全设置来测试@WebMvcTest : @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers(“/admin*”).access(“hasRole(‘ADMIN’)”).antMatchers(“/**”).permitAll().and().formLogin(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser(“user”).password(“password”).roles(“ADMIN”); } } 测试类是: @RunWith(SpringRunner.class) @WebMvcTest(value = ExampleController.class) public class ExampleControllerMockMVCTest { @Autowired private MockMvc mockMvc; @Test public void indexTest() throws Exception { mockMvc.perform(get(“/”)) .andExpect(status().isOk()) .andExpect(view().name(“index”)); } […]