I am newbie in writing unit tests. I tried something and saveProduct test passed but i don't know how to test paginated method and is it good approach to write test this way or not. Please tell me what am i doing wrong and how can i write proper unit test for my service implementation class ? Also do i need to test repository interface?
My code structure is below
@Repository
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
Optional<Page<Product>> findProductByMerchantId(Long id, Pageable pageable);
}
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {
private final ProductRepository repository;
public List<Product> getAllProducts(
Long merchantId, Integer pageNo, Integer pageSize, String sortBy) {
Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(sortBy));
Page<Product> pagedResult =
repository
.findProductByMerchantId(merchantId, paging)
.orElseThrow(
() ->
new IllegalStateException(
String.format("There is no product belong to %s ", merchantId.toString())));
return pagedResult.getContent();
}
public Product saveProduct(Product product) {
repository.save(product);
return product;
}
}
@ExtendWith(MockitoExtension.class)
class ProductServiceImplTest {
@Mock
ProductRepository productRepository;
@InjectMocks
ProductServiceImpl productServiceImpl;
@Test
void testGetAllProducts() {
Product product=new Product();
List<Product> list=new ArrayList<Product>();
list.add(product);
Pageable paging = PageRequest.of(0, 2, Sort.by("inventory"));
when(productServiceImpl.getAllProducts(2L,0,2,"inventory")).thenReturn(list);
// when(productRepository.findProductByMerchantId(2L,paging)).thenReturn(list);
productServiceImpl.getAllProducts(2L,0,2,"inventory");
verify(productRepository).findProductByMerchantId(2L,paging);
}
@Test
void testSaveProduct() {
Product product=new Product();
when(productServiceImpl.saveProduct(product)).thenReturn(product);
Product product1=productServiceImpl.saveProduct(product);
assertNotNull(product1);
verify(productRepository,times(1)).save(product);
}
}