Cecil Westerhof
Cecil Westerhof

Reputation: 183

How to test my @NotEmpty with JUnit

We have to remove almost every framework used in the code. I started with the @NotEmpty from Hibernate. It was the only class used from Hibernate, so low hanging fruit we thought.

I wrote the following implementation:

import        java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.FIELD;
import        java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import        java.lang.annotation.Target;

import        javax.validation.Constraint;
import        javax.validation.constraints.NotNull;
import        javax.validation.constraints.Size;
import        javax.validation.ReportAsSingleViolation;

@Documented
@Constraint(validatedBy = {})
@Target({ FIELD })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface NotEmpty {
    public abstract String message() default "Field has to be filled";
}

But it should be tested also of-course. So I wrote the following test:

import org.junit.Test;

class NotEmptyClass {
    @NotEmpty
    String notEmpty;

    NotEmptyClass(String value) {
        notEmpty = value;
    }
}

public class NotEmptyTest {
    @Test
    public void firstTest() {
        new NotEmptyClass(null);
    }
}

I would expect this test not to pass, but it does. So clearly I am doing something wrong, but I have no idea what. (This is the first time I really work with annotations.) I did some Googling but until now to no avail. So if someone could point me to the right direction …

============

I wrote a better version and published it on GitHub: My Java annotation example

Upvotes: 3

Views: 5343

Answers (1)

rob
rob

Reputation: 1286

I think your test does not fail because 1) you are not actually validating the object your are just initialising it and 2) you are not making any assertions

public class NotEmptyTest {
    @Test
    public void firstTest() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        NotEmptyClass obj = new NotEmptyClass(null);

        // Validate the object
        Set<ConstraintViolation<NotEmptyClass>> constraintViolations = validator.validate(obj);

        // This is the line that will cause your unit test to fail if there are not any violations
        Assert.assertEquals(1, constraintViolations.size());
    }
}

I would suggest reading this tutorial

Upvotes: 7

Related Questions