How can i test paginated result in spring boot?

Viewed 3992

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);
    }
}

1 Answers

Your approach was correct you have to mock the Repository interface and mock the call as you did.

If your repository method return List then use as below

 Mockito.when(appRepoitory.findProductByMerchantId(Mockito.anyString(), Mockito.any())).thenReturn(new ArrayList<>());

If your repository method return Page then follow as below.

Page<Product> pro= Mockito.mock(Page.class);
    Mockito.when(appRepoitory.findProductByMerchantId(Mockito.anyString(), Mockito.any())).thenReturn(pro);

And Verify you have these annotations in your class.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;

    @SpringBootTest
    @RunWith(MockitoJUnitRunner.class)
    public class ServiceTest {
    
    }
Related