Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
6.1 kB
1
Indexable
Never
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ProductServiceTest {
    @Test
    public void testGetProductsByCategory() {
        // Tạo mock của ProductRepository
        ProductRepository productRepository = Mockito.mock(ProductRepository.class);

        // Tạo đối tượng ProductService với mock ProductRepository
        ProductService productService = new ProductService(productRepository);

        // Tạo danh sách sản phẩm giả
        List<Product> fakeProducts = Arrays.asList(
                new Product("Product 1", "Category A"),
                new Product("Product 2", "Category A"),
                new Product("Product 3", "Category B")
        );

        // Định nghĩa hành vi cho phương thức findByCategory bằng QueryDSL
        Mockito.when(productRepository.findByCategory(Mockito.eq("Category A")))
                .thenReturn(fakeProducts.stream()
                        .filter(p -> p.getCategory().equals("Category A"))
                        .collect(Collectors.toList()));

        // Gọi phương thức kiểm thử
        List<Product> result = productService.getProductsByCategory("Category A");

        // Kiểm tra kết quả
        Assertions.assertEquals(2, result.size());
        Assertions.assertEquals("Product 1", result.get(0).getName());
        Assertions.assertEquals("Product 2", result.get(1).getName());
    }
}
////////////////////////////////////////////////////////////////////////////////////
public class Product {
    private String name;
    private BigDecimal price;

    // Constructors, getters, setters, etc.
}
//////////////////
public class ProductFilters {
    private BigDecimal minPrice;
    private BigDecimal maxPrice;

    // Constructors, getters, setters, etc.
}
////////////////
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Repository
public class ProductRepository {
    @PersistenceContext
    private EntityManager entityManager;
    
    public List<Product> findByFilters(ProductFilters filters) {
        QProduct qProduct = QProduct.product;
        BooleanBuilder predicate = new BooleanBuilder();

        if (filters.getMinPrice() != null) {
            predicate.and(qProduct.price.goe(filters.getMinPrice()));
        }

        if (filters.getMaxPrice() != null) {
            predicate.and(qProduct.price.loe(filters.getMaxPrice()));
        }

        // Thêm các điều kiện truy vấn khác dựa trên filters

        JPAQuery<Product> query = new JPAQuery<>(entityManager);
        query.from(qProduct).where(predicate);

        return query.fetch();
    }
}
///////////
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {
    private ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public List<Product> getProductsByFilters(ProductFilters filters) {
        return productRepository.findByFilters(filters);
    }
}
/////////
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

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

    @Autowired
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping
    public ResponseEntity<List<Product>> getProductsByFilters(ProductFilters filters) {
        List<Product> products = productService.getProductsByFilters(filters);
        return ResponseEntity.ok(products);
    }
}
////////////
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

public class ProductControllerTest {
    @Mock
    private ProductService productService;

    private ProductController productController;

    @BeforeEach
    public void setup() {
        productService = Mockito.mock(ProductService.class);
        productController = new ProductController(productService);
    }

    @Test
    public void testGetProductsByFilters() {
        // Tạo dữ liệu mẫu
        ProductFilters filters = new ProductFilters();
        filters.setMinPrice(BigDecimal.valueOf(100));
        filters.setMaxPrice(BigDecimal.valueOf(200));

        List<Product> products = new ArrayList<>();
        products.add(new Product("Product 1", BigDecimal.valueOf(150)));
        products.add(new Product("Product 2", BigDecimal.valueOf(180)));

        // Thiết lập behavior cho mock productService
        when(productService.getProductsByFilters(filters)).thenReturn(products);

        // Gọi phương thức kiểm thử
        ResponseEntity<List<Product>> response = productController.getProductsByFilters(filters);

        // Kiểm tra kết quả
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertEquals(products, response.getBody());
    }
}
////////////
Leave a Comment