I have a model class:
@Builder
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@GeneratedValue(strategy = GenerationType.AUTO)
@Type(type="uuid-char")
@Column(updatable = false, nullable = false, unique = true)
@Id
private UUID id;
@Column(updatable = true, nullable = false, unique = true)
@Email(message = "Enter a valid email")
private String email;
@NotNull(message = "First name cannot be empty")
@Size(min = 3, message = "First name character must be more than 3!")
private String firstName;
@Size(min = 3, message = "Last name character must be more than 3!")
private String lastName;
@Range(min = 21, max = 55, message = "Age must be between 21 and 55")
private int age;
@JsonIgnore
private Double accBalance;
@NotNull(message = "Gender cannot be empty")
private String gender;
@NotNull(message = "Country cannot be empty")
private String country;
@JsonProperty("Job Scope")
private String designation;
@CreationTimestamp
private Date createdAt;
@DateTimeFormat
private Date birthDate;
}
And this is my test class:
class EmployeeTest {
@Test
public void testObjectMethod() {
Employee object = new Employee();
object.equals(new Employee());
object.hashCode();
object.toString();
}
@Test
public void testAll() {
Employee object = new Employee();
object.equals(Employee.builder().build());
}
}
And this is my coverage. Basically it only covers 73.8%. What other tests do I need to do to achieve 100%? As this covers quite a lot and doesn't need much of thinking, I would like to target 100%. Appreciate any help or pointers.
CodePudding user response:
You need to do following
- write test for
equals
- write test for
hashcode
- write test case for
constructor
no-arg and all arg - test case for
setter
andgetter
for all attribute
you can write assertNotNull for hashCode
various tests.
CodePudding user response:
Because you use Lombok annotations, additional code will be generated in de compilation step. There is some debate in whether or not to test generated code but in general most people agree you should not test it. Don't test the framework!
So how do we then create coverage for this generated code? Very simple. You don't!
Even the Jacoco code coverage tool knows how silly it is to test generated code so it allows us to exclude it from the code coverage tool.
How? You have 2 options
- Annotate every class that uses a Lombok annotation with one additional Lombok annotation:
@Generated
OR (and this is the preferred method)
- create a
lombok.config
file in the project root folder and add the following configuration line:
lombok.addLombokGeneratedAnnotation = true
On your next coverage execution, you will see you have a higher percentage because all of Lombok's generated code will be excluded.
P.s.: note that when using @Data
, you add an equals
and hashCode
that matched all the fields instead of an id or unique business key, which is a bad idea when using JPA.