Creating a test case for a Rest API 

Now we will see how to test the database using the JPA and Hibernate of a Spring project. Here are the steps of how to test the database using JPA:

  1. Open the social_network project. The link is here: https://github.com/PacktPublishing/Learn-Spring-for-Android-Application-Development/tree/master/Chapter09/social_network.
  2. Now go to the testkotlin | com.packtpub.sunnat629.social_network package and create a file named ProfileRepositoryTest.kt with two annotations named @RunWith(SpringRunner::class) and @DataJpaTest.

Here is the code of the ProfileRepositoryTest.kt:

@RunWith(SpringRunner::class)
@DataJpaTest
class ProfileRepositoryTest {

@Autowired
private lateinit var entityManager: TestEntityManager

@Autowired
private lateinit var profileRepository: ProfileRepository

@Test
fun getUserTesting(){
val newProfile = getNewProfile()
val saveProfile = entityManager.merge(newProfile)

val foundProfile = profileRepository.getOne(saveProfile.id!!)

assertThat(foundProfile.username)
.isEqualTo(saveProfile.username)
}

private fun getNewProfile(): Profile {
return Profile( "naruto",
"12345",
"naruto123@gmail.com",
"Naruto",
"Uzumak")
}
}

The following is an explanation of the preceding code:

Now, we will insert a demo Profile object and check if the insertion is working or not. To begin with, we have to create a Profile object using the getNewProfile() function.

After this we save this profile as a new variable, such as this:

val saveProfile = entityManager.merge(newProfile)

Here, we used the entityManager.merge(), which will insert the profile in the database.

We also autowired the profileRepository now use this line to fetch the inserted profile by the ID:

val foundProfile = profileRepository.getOne(saveProfile.id!!)

Now we have used the assertThat() to check the given logic is correct or not. In this function, we have checked the created profile and the fetched profile:

 assertThat(foundProfile.username).isEqualTo(saveProfile.username)

Now, if there are any errors regarding insertion or communication with the database, it will return an error.

Here is the output of our test:

If you provide something as a false value, or the test encounters an error, it will output the following:

We have entered a profile name as naruto, but we tested the name Uzumak, which is why it didn't match. The result subsequently failed.