Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8488937
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T21:41:21+00:00 2026-06-10T21:41:21+00:00

I have a POJO called Browser that I’ve annotated with Hibernate Validator annotations. import

  • 0

I have a POJO called Browser that I’ve annotated with Hibernate Validator annotations.

import org.hibernate.validator.constraints.NotEmpty;

public class Browser {

    @NotEmpty
    private String userAgent;
    @NotEmpty
    private String browserName;

...

}

I’ve written the following unit test that tries to verify my Controller method catches validation errors.

@Test
public void testInvalidData() throws Exception {
    Browser browser = new Browser("opera", null);
    MockHttpServletRequest request = new MockHttpServletRequest();

    BindingResult errors = new DataBinder(browser).getBindingResult();
    // controller is initialized in @Before method
    controller.add(browser, errors, request);
    assertEquals(1, errors.getErrorCount());
}

Here’s my Controller’s add() method:

@RequestMapping(value = "/browser/create", method = RequestMethod.POST)
public String add(@Valid Browser browser, BindingResult result, HttpServletRequest request) throws Exception {
    if (result.hasErrors()) {
        request.setAttribute("errorMessage", result.getAllErrors());
        return VIEW_NAME;
    }

    browserManager.save(browser);

    request.getSession(false).setAttribute("successMessage",
            String.format("Browser %s added successfully.", browser.getUserAgent()));

    return "redirect:/" + VIEW_NAME;
}

The problem I’m experiencing is that result never has errors, so it’s like @Valid isn’t getting recognized. I tried adding the following to my test class, but it doesn’t solve the problem.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:path-to/WEB-INF/spring-mvc-servlet.xml"})

Does anyone know how I’d get @Valid to be recognized (and validated) when testing with JUnit?

Thanks,

Matt

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T21:41:22+00:00Added an answer on June 10, 2026 at 9:41 pm

    The validation is done before the call to the controller, so your test is not invoking this validation.

    There is another approach to testing controllers, where you dont invoke the controller directly. Instead you construct and call the URL that the controller is mapped on. Here is a good example of how to do this:
    http://rstoyanchev.github.com/spring-31-and-mvc-test/#1

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(loader=WebContextLoader.class, locations = {"classpath:/META-INF/spring/applicationContext.xml", "classpath:/META-INF/spring/applicationContext-test-override.xml", "file:src/main/webapp/WEB-INF/spring/webmvc-config.xml"})
    public class MyControllerTest {
    @Autowired
    WebApplicationContext wac;
    MockMvc mockMvc;
    
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webApplicationContextSetup(this.wac).build();
    }
    
    @Test
    @Transactional
    public void testMyController() throws Exception {
        this.mockMvc.perform(get("/mycontroller/add?param=1").accept(MediaType.TEXT_HTML))
        .andExpect(status().isOk())
        .andExpect(model().attribute("date_format", "M/d/yy h:mm a"))
        .andExpect(model().attribute("myvalue", notNullValue()))
        .andExpect(model().attribute("myvalue", hasSize(2)))
        .andDo(print());
    }
    }
    

    POM (need to use spring milestone repo):

        <!-- required for spring-test-mvc -->
        <repository>
            <id>spring-maven-milestone</id>
            <name>Spring Maven Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    ...
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test-mvc</artifactId>
            <version>1.0.0.M1</version>
            <scope>test</scope>
        </dependency>
    

    NOTE: the spring-mvc-test lib is not production ready yet. There are some gaps in the implementation. I think its planned to be fully implemented for spring 3.2.

    This approach is a great idea as it tests your controllers fully. Its easy to mess up your controller mappings, so these do really need to be unit tested.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a POJO that uses a service to do something: public class PlainOldJavaObject
Let's say I have following POJO's using Hibernate. public class User { private String
I am learning Hibernate and I am stuck with annotations. I have a POJO
I have a POJO class with a method annotated with @Transactional public class Pojo
I have a POJO class with hibernate annotations for each table in database. Also
We have a pojo that needs to have a list of integers. As an
I have the following POJO: public class SampleBean1 { @Id @GeneratedValue(generator = system-uuid) @GenericGenerator(name
I have a POJO, and a (currently not-yet-built) class that will return Lists of
I have a simple POJO mapped to a table using Hibernate. Which works just
Let's say I have a simple POJO class: public void Foo { public int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.