Commit 03cae237 authored by Perwaiz Ali's avatar Perwaiz Ali

Reactive CURD and Test cases

parents
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="D:/Gradle/gradle-7.5.1" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
<option name="useQualifiedModuleNames" value="true" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.javatechie</groupId>
<artifactId>spring-reactive-mongo-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-reactive-mongo-crud</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.javatechie.reactive;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringReactiveMongoCrudApplication {
public static void main(String[] args) {
SpringApplication.run(SpringReactiveMongoCrudApplication.class, args);
}
}
package com.javatechie.reactive.controller;
import com.javatechie.reactive.dto.ProductDto;
import com.javatechie.reactive.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService service;
@GetMapping
public Flux<ProductDto> getProducts(){
return service.getProducts();
}
@GetMapping("/{id}")
public Mono<ProductDto> getProduct(@PathVariable String id){
return service.getProduct(id);
}
@GetMapping("/product-range")
public Flux<ProductDto> getProductBetweenRange(@RequestParam("min") double min, @RequestParam("max")double max){
return service.getProductInRange(min,max);
}
@PostMapping
public Mono<ProductDto> saveProduct(@RequestBody Mono<ProductDto> productDtoMono){
System.out.println("controller method called ...");
return service.saveProduct(productDtoMono);
}
@PutMapping("/update/{id}")
public Mono<ProductDto> updateProduct(@RequestBody Mono<ProductDto> productDtoMono,@PathVariable String id){
return service.updateProduct(productDtoMono,id);
}
@DeleteMapping("/delete/{id}")
public Mono<Void> deleteProduct(@PathVariable String id){
return service.deleteProduct(id);
}
}
package com.javatechie.reactive.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ProductDto {
private String id;
private String name;
private int qty;
private double price;
}
package com.javatechie.reactive.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "products")
public class Product {
@Id
private String id;
private String name;
private int qty;
private double price;
}
package com.javatechie.reactive.repository;
import com.javatechie.reactive.dto.ProductDto;
import com.javatechie.reactive.entity.Product;
import org.springframework.data.domain.Range;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface ProductRepository extends ReactiveMongoRepository<Product,String> {
Flux<ProductDto> findByPriceBetween(Range<Double> priceRange);
}
package com.javatechie.reactive.service;
import com.javatechie.reactive.dto.ProductDto;
import com.javatechie.reactive.entity.Product;
import com.javatechie.reactive.repository.ProductRepository;
import com.javatechie.reactive.utils.AppUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Range;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
public Flux<ProductDto> getProducts(){
return repository.findAll().map(AppUtils::entityToDto);
}
public Mono<ProductDto> getProduct(String id){
return repository.findById(id).map(AppUtils::entityToDto);
}
public Flux<ProductDto> getProductInRange(double min,double max){
return repository.findByPriceBetween(Range.closed(min,max));
}
public Mono<ProductDto> saveProduct(Mono<ProductDto> productDtoMono){
System.out.println("service method called ...");
return productDtoMono.map(AppUtils::dtoToEntity)
.flatMap(repository::insert)
.map(AppUtils::entityToDto);
}
public Mono<ProductDto> updateProduct(Mono<ProductDto> productDtoMono,String id){
return repository.findById(id)
.flatMap(p->productDtoMono.map(AppUtils::dtoToEntity)
.doOnNext(e->e.setId(id)))
.flatMap(repository::save)
.map(AppUtils::entityToDto);
}
public Mono<Void> deleteProduct(String id){
return repository.deleteById(id);
}
}
package com.javatechie.reactive.utils;
import com.javatechie.reactive.dto.ProductDto;
import com.javatechie.reactive.entity.Product;
import org.springframework.beans.BeanUtils;
public class AppUtils {
public static ProductDto entityToDto(Product product) {
ProductDto productDto = new ProductDto();
BeanUtils.copyProperties(product, productDto);
return productDto;
}
public static Product dtoToEntity(ProductDto productDto) {
Product product = new Product();
BeanUtils.copyProperties(productDto, product);
return product;
}
}
spring:
data:
mongodb:
database: Productsdb
host: localhost
port: 27017
server:
port: 9292
\ No newline at end of file
package com.javatechie.reactive;
import com.javatechie.reactive.controller.ProductController;
import com.javatechie.reactive.dto.ProductDto;
import com.javatechie.reactive.service.ProductService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebFluxTest(ProductController.class)
class SpringReactiveMongoCrudApplicationTests {
@Autowired
private WebTestClient webTestClient;
@MockBean
private ProductService service;
@Test
public void addProductTest(){
Mono<ProductDto> productDtoMono=Mono.just(new ProductDto("102","mobile",1,10000));
when(service.saveProduct(productDtoMono)).thenReturn(productDtoMono);
webTestClient.post().uri("/products")
.body(Mono.just(productDtoMono),ProductDto.class)
.exchange()
.expectStatus().isOk();//200
}
@Test
public void getProductsTest(){
Flux<ProductDto> productDtoFlux=Flux.just(new ProductDto("102","mobile",1,10000),
new ProductDto("103","TV",1,50000));
when(service.getProducts()).thenReturn(productDtoFlux);
Flux<ProductDto> responseBody = webTestClient.get().uri("/products")
.exchange()
.expectStatus().isOk()
.returnResult(ProductDto.class)
.getResponseBody();
StepVerifier.create(responseBody)
.expectSubscription()
.expectNext(new ProductDto("102","mobile",1,10000))
.expectNext(new ProductDto("103","TV",1,50000))
.verifyComplete();
}
@Test
public void getProductTest(){
Mono<ProductDto> productDtoMono=Mono.just(new ProductDto("102","mobile",1,10000));
when(service.getProduct(any())).thenReturn(productDtoMono);
Flux<ProductDto> responseBody = webTestClient.get().uri("/products/102")
.exchange()
.expectStatus().isOk()
.returnResult(ProductDto.class)
.getResponseBody();
StepVerifier.create(responseBody)
.expectSubscription()
.expectNextMatches(p->p.getName().equals("mobile"))
.verifyComplete();
}
@Test
public void updateProductTest(){
Mono<ProductDto> productDtoMono=Mono.just(new ProductDto("102","mobile",1,10000));
when(service.updateProduct(productDtoMono,"102")).thenReturn(productDtoMono);
webTestClient.put().uri("/products/update/102")
.body(Mono.just(productDtoMono),ProductDto.class)
.exchange()
.expectStatus().isOk();//200
}
@Test
public void deleteProductTest(){
given(service.deleteProduct(any())).willReturn(Mono.empty());
webTestClient.delete().uri("/products/delete/102")
.exchange()
.expectStatus().isOk();//200
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment