@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTests {
@Autowired
UserService userSevice;
@Test
public void testAllUsers(){
List<User> users = userSevice.getAllUsers();
assertEquals(3, users.size());
}
}
In the preceding code, we have called getAllUsers and verified the total count. Let's test the single-user method in another test case:
// other methods
@Test
public void testSingleUser(){
User user = userSevice.getUser(100);
assertTrue(user.getUsername().contains("David"));
}
In the preceding code snippets, we just tested our service layer and verified the business logic. However, we can directly test the controller by using mocking methods.
First, we shall start with a simple API for getting all the users:
http://localhost:8080/user
The earlier method will get all the users. The Postman screenshot for getting all the users is as follows:
In the preceding screenshot, we can see that we get all the users that we added before. We have used the GET method to call this API.
Let's try to use the POST method in user to add a new user:
http://localhost:8080/user
Add the user, as shown in the following screenshot:
In the preceding result, we can see the JSON output:
{
"result" : "added"
}
Let's try generating the token (JWT) by calling the generate token API in Postman using the following code:
http://localhost:8080/security/generate/token
We can clearly see that we use subject in the Body to generate the token. Once we call the API, we will get the token. We can check the token in the following screenshot:
By using the existing token that we created before, we will get the subject by calling the get subject API:
http://localhost:8080/security/get/subject
The result will be as shown in the following screenshot:
In the preceding API call, we sent the token in the API to get the subject. We can see the subject in the resulting JSON.
You read an excerpt from Building RESTful Web Services with Spring 5 - Second Edition written by Raja CSP Raman. From this book, you will learn to build resilient software in Java with the help of the Spring 5.0 framework.