Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Shobhika

2200290120763
Springframework-

Ques 36.)1.Create an entity class in the model package.

package com.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;

// Getters and Setters


}
2.Create a repository interface in the repository package.
package com.example.repository;

import com.example.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends
JpaRepository<Product, Long> {
}
3.Create a service interface and implementation in the service
package.
package com.example.service;

import com.example.model.Product;
import java.util.List;

public interface ProductService {


List<Product> getAllProducts();
Product getProductById(Long id);
Product createProduct(Product product);
void deleteProduct(Long id);
}

package com.example.service.impl;

import com.example.model.Product;
import com.example.repository.ProductRepository;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;

@Override
public List<Product> getAllProducts() {
return productRepository.findAll();
}

@Override
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}

@Override
public Product createProduct(Product product) {
return productRepository.save(product);
}

@Override
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
}
4.Develop a REST controller in the controller package.
package com.example.controller;

import com.example.model.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;

@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}

@GetMapping("/{id}")
public ResponseEntity<Product>
getProductById(@PathVariable Long id) {
Product product = productService.getProductById(id);
if (product != null) {
return new ResponseEntity<>(product, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@PostMapping
public Product createProduct(@RequestBody Product product)
{
return productService.createProduct(product);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable
Long id) {
productService.deleteProduct(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

Ques 37.)
Set Up Your Spring Boot Project
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Create a Sample REST Controller

package com.example.controller;

import com.example.model.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;

@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}

@GetMapping("/{id}")
public ResponseEntity<Product>
getProductById(@PathVariable Long id) {
Product product = productService.getProductById(id);
if (product != null) {
return new ResponseEntity<>(product, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@PostMapping
public Product createProduct(@RequestBody Product product)
{
return productService.createProduct(product);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable
Long id) {
productService.deleteProduct(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

Write Tests for the REST Controller


package com.example.controller;

import com.example.model.Product;
import com.example.service.ProductService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.autoconfigure.web.servlet.WebMvc
Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import
org.springframework.test.web.servlet.result.MockMvcResultMatch
ers;

import java.util.Arrays;
import java.util.Optional;

import static org.mockito.ArgumentMatchers.any;


import static org.mockito.Mockito.when;
import static
org.springframework.test.web.servlet.request.MockMvcRequestB
uilders.*;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatch
ers.*;

@WebMvcTest(ProductController.class)
public class ProductControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private ProductService productService;
@Test
public void testGetAllProducts() throws Exception {

when(productService.getAllProducts()).thenReturn(Arrays.asList(
new Product(1L, "Product A", 10.0), new Product(2L, "Product B",
20.0)));

mockMvc.perform(get("/api/products"))
.andExpect(status().isOk())

.andExpect(content().contentType(MediaType.APPLICATION_JS
ON))
.andExpect(jsonPath("$[0].name").value("Product A"))
.andExpect(jsonPath("$[1].name").value("Product B"));
}

@Test
public void testGetProductById() throws Exception {
when(productService.getProductById(1L)).thenReturn(new
Product(1L, "Product A", 10.0));

mockMvc.perform(get("/api/products/1"))
.andExpect(status().isOk())

.andExpect(content().contentType(MediaType.APPLICATION_JS
ON))
.andExpect(jsonPath("$.name").value("Product A"));
}
@Test
public void testCreateProduct() throws Exception {
Product product = new Product(3L, "Product C", 30.0);

when(productService.createProduct(any(Product.class))).thenRet
urn(product);

mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\": \"Product C\", \"price\": 30.0}"))
.andExpect(status().isOk())

.andExpect(content().contentType(MediaType.APPLICATION_JS
ON))
.andExpect(jsonPath("$.name").value("Product C"));
}

@Test
public void testDeleteProduct() throws Exception {
mockMvc.perform(delete("/api/products/1"))
.andExpect(status().isNoContent());
}
}

Ques 38.)
1. Set Up Your Spring Boot Project

Ensure your project is set up with necessary dependencies for


both the backend and testing tools.

Pom.xml:
<dependencies>

<!-- Spring Boot and Web dependencies -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

<!-- Spring Boot Test -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<!-- Selenium dependencies for frontend testing -->


<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.1
Create a Simple Spring Boot Application

Application.java:

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

package com.example.demo.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;
@Controller

public class HomeController {

@GetMapping("/")

public String home(Model model) {

model.addAttribute("message", "Hello, World!");

return "home";

home.html (Thymeleaf template):<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<title>Home</title>

</head>

<body>

<h1 th:text="${message}"></h1>

</body>

</html>

package com.example.demo;

import org.junit.jupiter.api.AfterAll;

import org.junit.jupiter.api.BeforeAll;

import org.junit.jupiter.api.Test;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.boot.test.web.server.LocalServerPort;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

public class HomePageTest {

@LocalServerPort

private int port;

private static WebDriver driver;

@BeforeAll

public static void setup() {

// Set the path to the chromedriver executable

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

driver = new ChromeDriver();

@AfterAll

public static void tearDown() {


if (driver != null) {

driver.quit();

@Test

public void testHomePage() {

driver.get("http://localhost:" + port);

WebElement h1 = driver.findElement(By.tagName("h1"));

assertThat(h1.getText()).isEqualTo("Hello, World!");

You might also like