Frodo
Frodo

Reputation: 46

Spring Controller Unit Test

I'm using Spring Boot, Spring Data JPA, and JUnit 5.

All IDs in entities are automatically generated by DB (@GeneratedValue).

So all entities don't include any constructors and setter methods for initializing ID.

When I implement unit tests for controllers (@WebMvcTest), all ids of entities are null.

The problem is that some endpoints respond id, so when I implement unit tests for them, they respond null, that is, fail the test.

How can I implement unit tests for controllers that respond ID generated by DB?

Upvotes: 0

Views: 100

Answers (1)

VaibS
VaibS

Reputation: 1893

You can add Getter methods to class and then use ObjectMapper to set id field.

Employee employee = new ObjectMapper().readValue(""{\"id\": \"1\"}", Employee.class);

Other approach is to use reflection in JUnit to set that field.

    Employee employee = new Employee();

    Field field = Employee.class.getDeclaredField("id");
    field.setAccessible(true);
    field.set(employee, "1");

Other ways to use reflection: Access a private field for a junit test

Upvotes: 1

Related Questions