Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Different test results when running from JUnit and Maven

I am facing a problem I don't know how to solved. I am developing a Spring MVC application with its unit&integration tests. Everything runs fine under JUnit (Run As -> JUnit Test) but fails when I it under Maven (Surefire 2.10) I got two type of errors:

Model Test

testFileNameCannotBeNull(es.kazbeel.geckobugtracker.model.AttachmentTest): Unexpected exception, expected<org.hibernate.exception.ConstraintViolationException> but was<org.hibernate.PropertyValueException>

Controller test

testCreateEnvironmentPost_withBindingResultErrors(es.kazbeel.geckobugtracker.web.controller.admin.EnvironmentControllerTest): View name expected:</admin/environments/CreateEnvironment> but was:<redirect:/admin/environments/ViewEnvironments>

AttachmentTest (only the method that fails)

@Test(expected = ConstraintViolationException.class)
@DatabaseSetup("AttachmentTest.xml")
@Transactional
public void testFileNameCannotBeNull () {

    Session session = sessionFactory.getCurrentSession();

    Issue issue = (Issue) session.get(Issue.class, 1);
    User author = (User) session.get(User.class, 1);

    Attachment attch = AttachmentBuilder.attachment()
                                        .withIssue(issue)
                                        .withAuthor(author)
                                        .withFileName(null)
                                        .withFileSize(new Long(0))
                                        .withFileMimeType("file_mimetype")
                                        .build();

    session.save(attch);
    session.flush();
    session.clear();
}

In this case, the model is configured in a hbm.xml. The property is as follows

<property generated="never" lazy="false" length="255" name="fileName" column="FILE_NAME" not-null="true" type="java.lang.String">

EnvironmentControllerTest (only the method that fails)

@Test
public void testCreateEnvironmentPost_withBindingResultErrors () throws Exception {

    mockMvc.perform(post("/admin/environments/CreateEnvironment").param("name", ""))
           .andExpect(view().name("/admin/environments/CreateEnvironment"))
           .andExpect(model().hasErrors())
           .andExpect(model().size(1))
           .andExpect(model().attributeExists("environment"));

    verify(issueService, never()).saveEnvironment(any(Environment.class));
}

EnvironmentController (only method)

@RequestMapping(value = "/CreateEnvironment", method = RequestMethod.POST)
public String createEnvironmentPost (@Valid @ModelAttribute("environment") Environment environment,
                                     BindingResult result) {

    LOG.debug("Creating new Environment");

    if (result.hasErrors() == true) {
        LOG.debug("The environment is not valid: {}", result.getFieldError().getDefaultMessage());

        return CREATE_URL;
    }

    try {
        issueService.saveEnvironment(environment);
    } catch (DataIntegrityViolationException ex) {
        LOG.debug(ex.getMessage());

        return CREATE_URL;
    }

    return "redirect:" + VIEW_URL;
}

pom.xml (only related to surefire)

  <plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.10</version>
    <executions>
      <execution>
        <id>default-test</id>
        <phase>test</phase>
        <goals>
          <goal>test</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Sincerely, I am lost (I don't even know what kind of information should I show you regarding this problem).

Has anyone an idea of what might be happening? I haven't found anything similar surfing on the Internet.

! UPDATE !

Removing the dependency (see below) in pom.xml (but keeping javax.validation) I get the same exceptions running the tests under JUnit.

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.1.Final</version>
    </dependency>

OK! This is a step ahead but, this makes me wonder whether this assertion is true. I was convinced that validation is the very first verification/check but it seems Hibernate's properties' check takes over firstly. Am I right?

like image 290
kazbeel Avatar asked Oct 19 '25 06:10

kazbeel


1 Answers

! SOLVED !

First

Problem. It seems that the is a kind of incompatibility when including both validators in the same project:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.1.Final</version>
    </dependency>

Solution. I removed the javax.validation from the pom.xml.

NOTE: Please, if I am wrong I would really appreciate an explanation.

Second

Problem. After solving the first problem I still didn't get the tests running successfully.

Solution. I found the solution on the official webpage of Hibernate Validator.

Unified Expression Language (EL) Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages. When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container. In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance you can add the following two dependencies to use the JSR 341 reference implementation:

    <dependency>
       <groupId>javax.el</groupId>
       <artifactId>javax.el-api</artifactId>
       <version>2.2.4</version>
    </dependency>
    <dependency>
       <groupId>org.glassfish.web</groupId>
       <artifactId>javax.el</artifactId>
       <version>2.2.4</version>
    </dependency>
like image 56
kazbeel Avatar answered Oct 20 '25 20:10

kazbeel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!