In today’s tutorial, we are going to leverage Postman framework to successfully test RESTful Web Services.
We will also discuss a simple JUnit test case, which is calling the getAllUsers method in userService. We can check the following code:
@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:
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:
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.
I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…
Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…
Once we learn how to deploy an Ubuntu server, how to manage users, and how…
Key-takeaways: Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…
While developing a web application, or setting dynamic pages and meta tags we need to deal with…
Software architecture is one of the most discussed topics in the software industry today, and…