0% found this document useful (0 votes)
4 views9 pages

Spring and Spring Boot Related Ptogram

The document provides a comprehensive guide on creating a basic Spring Boot application using Spring Initializr, including steps to set up the project and create RESTful APIs. It also includes testing examples for RESTful web services using JUnit and RestAssured, demonstrating how to test various endpoints. Additionally, it covers integration testing for a user controller with multiple test cases for retrieving, creating, updating, and deleting users.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Spring and Spring Boot Related Ptogram

The document provides a comprehensive guide on creating a basic Spring Boot application using Spring Initializr, including steps to set up the project and create RESTful APIs. It also includes testing examples for RESTful web services using JUnit and RestAssured, demonstrating how to test various endpoints. Additionally, it covers integration testing for a user controller with multiple test cases for retrieving, creating, updating, and deleting users.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Program No.

8
Create industry-oriented application using Spring
Framework
Spring Boot is the most popular Java framework that is used for
developing RESTful web applications. In this article, we will see how to
create a basic Spring Boot application.
Spring Initializr is a web-based tool using which we can easily generate
the structure of the Spring Boot project. It also provides various different
features for the projects expressed in a metadata model. This model allows
us to configure the list of dependencies that are supported by JVM. Here,
we will create the structure of an application using Spring Initializr and
then use an IDE to create a sample GET route.
Therefore, to do this, the following steps are followed:
Step 1: Go to Spring Initializr
Fill in the details as per the requirements. For this application:
Project: Maven
Language: Java
Spring Boot: 3.1.5
Packaging: JAR
Java: 17
Dependency: Spring Web
IDE: IntelliJ IDEA
NOTE: For creating a simple application in Java Spring Boot we can import
our code directly into various IDEs:
● Spring Tool Suite(STS)
● IntelliJ IDEA
● VSCode
Here, we have used IntelliJ IDEA for creating a basic Spring Boot
application
Step 2: Specify Group Id and Artifact Id. Here we have provided the
Group name as “com.gfg” and the Artifact ID as “Spring Boot app”.
Step 3: Click on Generate which will download the starter project.
Step 4: Extract the zip file. Now open a suitable IDE and then go
to File->New->Project from existing sources->Spring-boot-app and
select pom.xml. Click on import changes on prompt and wait for the project
to sync.

Note: In the Import Project for Maven window, make sure you choose the
same version of JDK which you selected while creating the project.
Step 5: Go to src->main->java->com.gfg.Spring.boot.app, create a java
class with name as Controller and add the annotation @RestController.
Now create a GET API as shown below:

Java

@RestController
public class Controller
{
@GetMapping("/")

public String home()

{
String str= "<html><body><font color=\"green\">"+ "<h1>WELCOME To
GeeksForGeeks</h1>"+ "</font></body></html>"; return str;

}
@RequestMapping(

method = { RequestMethod.GET },

value = { "/gfg" })
public String info()

{
String str2= "<html><body><font color=\"green\">"+ "<h2>GeeksForGeeks is a
Computer"+ " Science portal for Geeks. "+ "This portal has been "+ "created to
provide well written, "+ "well thought and well explained "+ "solutions for selected
questions."+ "</h2></font></body></html>"; return str2;
}
}

Step 6: This application is now ready to run. Run


the SpringBootAppApplication class and wait for the Tomcat server to
start.
Note: The default port of the Tomcat server is 8080 and can be changed in
the application.properties file.
Step 7: Now go to the browser and enter the URL localhost:8080.
Observe the output and now do the same for localhost:8080/gfg

OUTPUT:
Program No. 9

Test RESTful web services using Spring Boot.

A popular Java library for testing RESTful APIs.


YourRestController.java:

package com.yourcompany.yourproject;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YourRestController {

@GetMapping("/api/hello")
public String hello() {
return "Hello, World!";
}
}

YourRestControllerTest.

package com.yourcompany.yourproject;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.when;
import static org.hamcrest.Matchers.equalTo;

public class YourRestControllerTest {


@BeforeEach
void setUp() {
standaloneSetup(new YourRestController());
}
@Test
void testHelloEndpoint() {
when().
get("/api/hello").
then().
statusCode(200).
body(equalTo("Hello, World!"));
}
}
Program No. 10
Test RESTful web services using Spring Boot.

A popular Java library for testing RESTful APIs.


YourRestController.java:

package com.yourcompany.yourproject;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YourRestController {

@GetMapping("/api/hello")
public String hello() {
return "Hello, World!";
}
}

YourRestControllerTest.java:

package com.yourcompany.yourproject;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.when;
import static org.hamcrest.Matchers.equalTo;

public class YourRestControllerTest {


@BeforeEach
void setUp() {
standaloneSetup(new YourRestController());
}
@Test
void testHelloEndpoint() {
when().
get("/api/hello").
then().
statusCode(200).
body(equalTo("Hello, World!"));
}
}
Program No. 11
Test Frontend web application with Spring Boot
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMo
ckMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;

import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testGetUserById() throws Exception {
// Arrange
long userId = 1L;

// Act
ResultActions result = mockMvc.perform(get("/api/users/{id}",
userId));

// Assert
result.andExpect(status().isOk())

.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(userId))
.andExpect(jsonPath("$.name").value("John Doe"))

.andExpect(jsonPath("$.email").value("[email protected]"));
}

@Test
public void testCreateUser() throws Exception {
// Arrange
String userJson =
"{\"name\":\"Alice\",\"email\":\"[email protected]\"}";

// Act
ResultActions result = mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson));

// Assert
result.andExpect(status().isCreated())
.andExpect(header().string("Location",
"http://localhost/api/users/2"));
}

@Test
public void testUpdateUser() throws Exception {
// Arrange
long userId = 1L;
String updatedUserJson = "{\"name\":\"Updated
Name\",\"email\":\"[email protected]\"}";

// Act
ResultActions result = mockMvc.perform(put("/api/users/{id}",
userId)
.contentType(MediaType.APPLICATION_JSON)
.content(updatedUserJson));

// Assert
result.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(userId))
.andExpect(jsonPath("$.name").value("Updated Name"))

.andExpect(jsonPath("$.email").value("[email protected]"));
}

@Test
public void testDeleteUser() throws Exception {
// Arrange
long userId = 1L;

// Act
ResultActions result =
mockMvc.perform(delete("/api/users/{id}", userId));

// Assert
result.andExpect(status().isOk());
}
}

You might also like