GVKun编程网logo

如何测试Spring 2.5控制器上使用的活页夹/属性编辑器

14

如果您想了解如何测试Spring2.5控制器上使用的活页夹/属性编辑器的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于java–Spring转换器或属性编辑器,用于将多个请求参数转换为Ob

如果您想了解如何测试Spring 2.5控制器上使用的活页夹/属性编辑器的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于java – Spring转换器或属性编辑器,用于将多个请求参数转换为Object?、java – 单元测试Spring RESTful控制器时“内容类型未设置”、java – 如何测试spring配置类?、java-Spring属性编辑器仅适用于表单吗?的有价值的信息。

本文目录一览:

如何测试Spring 2.5控制器上使用的活页夹/属性编辑器

如何测试Spring 2.5控制器上使用的活页夹/属性编辑器

我有一个带注释的控制器,该方法带有一种期望模型和绑定结果的方法

@RequestMapping(method = RequestMethod.POST)  public ModelAndView submit(@ModelAttribute(“user”) User user, BindingResult bindingResult) {     //do something}

如何测试绑定结果?如果我用用户和绑定结果调用该方法,那么我不会测试绑定过程。我认为,有些东西需要MockHttpServletRequest并返回模型和绑定结果,有什么建议吗?

答案1

小编典典

您是要测试绑定(在调用此方法之前发生)还是要测试“提交”处理程序方法?

您可以使用以下方法测试绑定:

 @Test    public void testHandlerMethod() {        final MockHttpServletRequest request = new MockHttpServletRequest("post", "/...");        request.setParameter("firstName", "Joe");        request.setParameter("lastName", "Smith");        final User user = new User();        final WebDataBinder binder = new WebDataBinder(user, "user");        binder.bind(new MutablePropertyValues(request.getParameterMap()));        final ModelAndView mv = controllerTestInstance.submit(user, binder.getBindingResult());        // Asserts...    }

java – Spring转换器或属性编辑器,用于将多个请求参数转换为Object?

java – Spring转换器或属性编辑器,用于将多个请求参数转换为Object?

具体示例是对Date对象的(2011,11,24,8,10,AM)请求参数的Convertor / propertyeditor的实现?

假设我的UI使用了一个小部件,它使用6个html表单字段作为日历(2011,AM) – 这非常不方便.

理想的解决方案是,如果参数只有一个 – “yyyy:MM:dd:hh:mm:aa”,@ DateTimeFormat注释在字段上,并且WebDataBinder已经使用DefaultConversionService joda-time设置在类路径上.

但我必须保持外观和感觉,并使用该小部件.在handler方法中进行转换也会使验证复杂化.知道如何在不处理处理程序方法的情况下做到这一点吗?

最佳答案
如果您创建一个自定义包装器对象,其中包含每个输入参数的字段,则将使用public … handlerMethod(InputDate date)填充它.然后,在同一个类中,您可以使用toDateTime(),它将根据输入构造DateTime.

您还可以使用自定义WebArgumentResolver并在方法签名中使用自定义注释,例如@InputDate.

java – 单元测试Spring RESTful控制器时“内容类型未设置”

java – 单元测试Spring RESTful控制器时“内容类型未设置”

我有一个类似于这个的Rest控制器:

@RestController
public class UserRestController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/activate",method = RequestMethod.POST)
    public ResponseEntityrequired = true) final String email,@RequestParam(required = true) final String key) {

        UserDTO userDTO = userService.activateAccount(email,key);
        return new ResponseEntity

当我使用Postman调用它并且我不发送’key’参数时,我收到此JSON消息:

{
    "timestamp": 1446211575193,"status": 400,"error": "Bad Request","exception": "org.springframework.web.bind.MissingServletRequestParameterException","message": "required String parameter 'key' is not present","path": "/user/activate"
}

另一方面,我正在使用JUnit和mockmvc Spring实用程序测试此方法.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class UserRestControllerTest {

    private static mockmvc mockmvc;

    @Mock
    private UserService userService;

    @InjectMocks
    private UserRestController userRestController;

    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);
        mockmvc = mockmvcBuilders
                .standalonesetup(userRestController)
                .setMessageConverters(
                        new MappingJackson2HttpMessageConverter(),new Jaxb2RootElementHttpMessageConverter()).build();

    }

    @Test
    public void testActivaterequiredParams() throws Exception {

        mockmvc.perform(
                mockmvcRequestBuilders.post("/user/activate")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .accept(MediaType.APPLICATION_JSON))
                .andDo(mockmvcResultHandlers.print())
                .andExpect(mockmvcResultMatchers.status().isBadRequest())
                .andExpect(
                        mockmvcResultMatchers.content().contentType(
                                UtilsUnitTest.APPLICATION_JSON_UTF8))
                .andExpect(
                        jsonPath(
                                "message",is("required String parameter 'email' is not present")));

     }
}

但是当我执行此测试时,我注意到响应不是JSON消息.事实上,我得到一个例外:

java.lang.AssertionError: Content type not set

特别是,完成的结果是

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /user/activate
          Parameters = {}
             Headers = {Content-Type=[application/x-www-form-urlencoded]}

             Handler:
                Type = com.company.controller.UserRestController
              Method = public org.springframework.http.ResponseEntityjava.lang.String)

               Async:
       Async started = false
        Async result = null

  Resolved Exception:
                Type = org.springframework.web.bind.MissingServletRequestParameterException

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 400
       Error message = required String parameter 'email' is not present
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

我推断当抛出异常时,这不会转换为JSON格式(当我发送电子邮件和关键参数时,我得到了正确的JSON结果)

问题很明显:如果抛出异常,我应该在单元测试配置中更改什么来获取JSON错误消息?

最佳答案
问题是在断言失败后测试停止:

.andExpect(mockmvcResultMatchers.content().contentType(UtilsUnitTest.APPLICATION_JSON_UTF8))

除此之外,jsonPath(“message”…不会点击任何内容.要验证返回的错误消息,请使用mockmvcResultMatchers.status().reason(< ResultMatcher>).

以下测试应该完成这项工作:

@Test
public void testActivaterequiredParams() throws Exception {
    final ResultActions result = mockmvc
            .perform(mockmvcRequestBuilders.post("/user/activate")
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON))
            .andDo(mockmvcResultHandlers.print());
    result.andExpect(mockmvcResultMatchers.status().isBadRequest());
    result.andExpect(mockmvcResultMatchers.status().reason(is("required String parameter 'email' is not present")));
}

但是考虑一下这个(测试错误信息)是不是一个好主意,也许看看this discussion.

java – 如何测试spring配置类?

java – 如何测试spring配置类?

我有一个spring应用程序配置类,其中实例bean.

应用类:

@Configuration
@EnableAspectJAutoproxy
@EnableSpringDataWebSupport
@EnableTransactionManagement
@ComponentScan(basePackageClasses = Application.class)
@PropertySource(value = {"classpath:foo.properties"})
@EnableJpaRepositories(basePackageClasses = Application.class)
@EnableJpaAuditing
public class Application {

    @Inject
    private Environment env;

    @Bean
    JndiTemplate jndiTemplate() {
        return new JndiTemplate();
    }

    @Bean
    public DataSource dataSource() {        
        DataSource dataSource = getDataSource();
        if (dataSource == null) {
            dataSource = new BasicDataSource();
            ((BasicDataSource) dataSource).setUsername(env.getProperty("jdbc.user"));
            ((BasicDataSource) dataSource).setPassword(env.getProperty("jdbc.password""));

            ((BasicDataSource) dataSource).setDriverClassName(env.getProperty("jdbc.driverClassName"));
            ((BasicDataSource) dataSource).setUrl(env.getProperty("jdbc.url"));
        }
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        EntityManagerFactory factory = entityManagerFactory().getobject();
        return new JpaTransactionManager(factory);
    }

    //....
}

MvcConfiguration类:

@Configuration
@ComponentScan(basePackageClasses = Application.class,includeFilters = @Filter({Controller.class,Component.class}),useDefaultFilters = true)
class MvcConfiguration extends WebMvcConfigurationSupport {
    private static final String MESSAGES = "classpath:/i18n";

    private static final String VIEW_PREFIX = "/WEB-INF/views/";

    @Inject
    private Environment env;

    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
        requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
        requestMappingHandlerMapping.setUseTrailingSlashMatch(true);

        return requestMappingHandlerMapping;
    }

    @Bean(name = "messageSource")
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(MESSAGES);
        messageSource.setCacheSeconds(5);

        return messageSource;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/").addResourceLocations("/static/**");
    }

    @Bean
    public MultipartResolver filterMultipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(Long.parseLong(env.getProperty("multipart.max.size")));
        return resolver;
    }

    //....

}

和SecurityConfiguration类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    //....

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //logout por POST con el valor de token csrf
        http.authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .failureUrl("/login?error=1")
                .loginProcessingUrl("/authenticate")
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/signin")
                .permitAll();
    }

}

我如何用JUnit测试它们?如何测试bean是在spring上下文中创建的?

最佳答案
我相信这只能通过集成测试来实现.

单元测试的目的不是检查整个Spring Context是否成功创建.

您可以使用模拟等测试单元测试的每个配置方法,以检查它们是否正常,但整个Spring Context事物是一个集成测试.

我通过执行Spring Docs所谓的“Spring Unit Test”(对我而言更像是控制器视图的集成测试)来进行此配置测试

我们的想法是,如果您可以为Controller集成测试运行Spring Context,那么您的配置就可以了.

关于如何进行这种测试的春季文档有一整章.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html

java-Spring属性编辑器仅适用于表单吗?

java-Spring属性编辑器仅适用于表单吗?

我正在开发一个Spring应用程序,该应用程序只是在一组数据中搜索符合某些条件的事物.有两个主要视图:一个是简单的表单,可让用户配置搜索条件,而另一个则将结果显示为表格.

搜索字段之一是一组封闭的选项(大约10个).在代码的下面,我想将此作为枚举类进行处理. Web表单包括一个下拉菜单,允许用户从此集合中选择一个选项.我使用了form:select来执行此操作,并填充了一组描述值的字符串.

为了使表示和业务逻辑分开,枚举类对这些字符串不了解,因此我创建了一个属性编辑器以在两者之间进行转换.当我加载表单时,将选择控件设置为与我给它的枚举值关联的字符串.提交表单时,字符串将转换回我的枚举类型.一切正常.

对于结果页面(不是表单),我只是将要显示的数据添加到ModelMap中.目前,我必须先将枚举类型转换为字符串,然后才能将其添加到地图中.我想做的就是将枚举添加到地图中,并让属性编辑器在后台为我转换它,就像在表单中一样.我不知道如何.是否有可能做到这一点?也许我缺少真正明显的东西?

最佳答案
您可以使用Spring Tablib

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

并使用转换标记

<!--If you have a command which command name is account-->
<!--Default command name used in Spring is called command-->
<spring:bind path="account.balance">${status.value}</spring:bind>

要么

<spring:bind path="account.balance">
    <spring:transform value="${account.balance}"/>
</spring:bind>

要么

<!--Suppose account.balance is a BigDecimal which has a propertyeditor registered-->
<spring:bind path="account.balance">
    <spring:transform value="${otherCommand.anotherBigDecimalProperty}"/>
</spring:bind>

关于值属性

The value can either be a plain value to transform (a hard-coded String value in a JSP or a JSP expression),or a JSP EL expression to be evaluated (transforming the result of the expression). Like all of Spring’s JSP tags,this tag is capable of parsing EL expressions itself,on any JSP version.

其API

Provides transformation of variables to String,using an appropriate custom propertyeditor from BindTag (can only be used inside BindTag)

如果您使用MultiActionController,我建议您使用Dummy Command类作为波纹管

public class Command {

    public BigDecimal bigDecimal;
    public Date date;
    /**
      * Other kind of property which needs a propertyeditor
      */

    // getter's and setter's

}

在您的MultiActionController内部

public class AccountController extends MultiActionController {

    @Autowired
    private Repository<Account,Integer> accountRepository;

    public AccountController() {
        /**
          * You can externalize this WebBindingInitializer if you want
          *
          * Here it goes as a anonymous inner class
          */
        setWebBindingInitializer(new WebBindingInitializer() {
            public void initBinder(WebDataBinder dataBinder,WebRequest request) {
                binder.registerCustomEditor(BigDecimal.class,new CustomNumberEditor(BigDecimal.class,numberFormat,true));
                binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"),true));
            }
        });
    }

    public ModelAndView(HttpServletRequest request,HttpServletResponse response) throws Exception {
        return new ModelAndView()
                   .addAllObjects(
                       createBinder(request,new Command())
                      .getBindingResult().getModel())
                   .addobject(accountRepository.findById(Integer.valueOf(request.getParameter("accountId"))));
    }

}

在您的JSP中

<c:if test="{not empty account}">
   <!--If you need a BigDecimal propertyeditor-->
   <spring:bind path="command.bigDecimal">
       <spring:transform value="${account.balance}"/>
   </spring:bind>
   <!--If you need a Date propertyeditor-->
   <spring:bind path="command.date">
       <spring:transform value="${account.joinedDate}"/>
   </spring:bind>
</c:if>

当您的Target命令没有提供需要在另一个命令中使用的propertyeditor时,这将很有用.

关于如何测试Spring 2.5控制器上使用的活页夹/属性编辑器的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于java – Spring转换器或属性编辑器,用于将多个请求参数转换为Object?、java – 单元测试Spring RESTful控制器时“内容类型未设置”、java – 如何测试spring配置类?、java-Spring属性编辑器仅适用于表单吗?的相关知识,请在本站寻找。

本文标签: