Spring Boot Project
Spring Boot Project
Spring Boot Project
Spring boot Starter test is the primary dependency to for testing that spring boot applications.
If you open the pom.xml file will see the spring boot starter Test dependency here like this:
Now create the following packages and class in the project like this :
Edit the Employee class like this :
package net.javaguides.springboot.model;
import jakarta.persistence.*;
import lombok.*;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name="employees")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable =false)
}
Edit the EmployeeRepository class like this :
package net.javaguides.springboot.repository;
import net.javaguides.springboot.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
spring.jpa.show-sql=true
and when we run the application we can see the table is getting created in the
database like this:
H2 Database
Here in our project we are using @DataJpaTest to test the repository layer which
may connected to any database may be mysql , sql , postgree sql etc.
But in case of unit testing the repository layer we don’t need to connect
repository layer to the real database. Because thumb rule is while unit testing
the individual component, the component may be depending on other dependencies and
database. But in unit testing it should depend upon the inmemory database to store
and retrieve the data or it should depend upon the mock dependency.
So @DataJpaTest Dependency will auto configured the inmemory database for testing
purpose. Also for repository layer we are not going to use mockito because
repository layer don’t have any dependences.
But in case of while testing the Service layer and controller layer we are going
to use the Mockito because conrollet layer is depends upon service layer and
service layer is depends upon repository layer.
We are going to use BDD style syntax.
(Behaviour-driven development)
Here in given section we setup the conditions and in when section we will setup
that what action we can take here against the predefined conditions.
And next comes the then section where we verify the output of the when section.