I am trying to do testing my save method in my service impl class. It has Page as return type. The test succeeds but I am writting something wrong because it succeeds for all the cases which normally shouldn't Please see my code below.
Service Class Implementation
@Service
@Transactional
public class CompanyServiceImpl implements CompanyService {
private final CompanyRepository companyRepository;
public CompanyServiceImpl(CompanyRepository companyRepository) {
this.companyRepository = companyRepository;
}
@Override
public Page<Company> findAll(Pageable pageable) {
Page<Company> result = companyRepository.findAll(pageable);
return result;
}
@Override
public Page<Company> searchCompany(String companyName, Long companyGroupId, Pageable pageable) {
Page<Company> result = companyRepository.findByParametersWeb(companyName,companyGroupId,pageable);
return result;
}
@Override
public Optional<Company> findById(Long id) {
Optional<Company> entity = companyRepository.findById(id);
return entity;
}
@Override
public Company save(Company company) {
Company entity = companyRepository.save(company);
return entity;
}
@Override
public void delete(Long id) {
companyRepository.deleteById(id);
}
}
Testing Service class
class CompanyServiceImplTest {
@Mock
private CompanyRepository companyRepository;
private CompanyService companyService;
private Company company;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
companyService = new CompanyServiceImpl(companyRepository);
company = new Company();
company.setName("company");
company.setCompanyGroupId(1L);
}
@Test
void searchCompany() {
List<Company> companies = new ArrayList<>();
Pageable pageable= PageRequest.of(0,5);
Page<Company> result = new PageImpl<>(companies,pageable,1);
when(companyRepository.findByParametersWeb(anyString(),anyLong(),any(Pageable.class))).thenReturn(result);
Page<Company> newResult = companyService.searchCompany("giorgos",1L,pageable);
assertEquals(newResult.getTotalElements(),result.getTotalElements());
}
}
Finally My Company Repository
@Repository
public interface CompanyRepository extends JpaRepository<Company, Long> {
@Query("SELECT a FROM Company a WHERE (:name is null or ((a.name LIKE :name AND LENGTH(:name) > 0) OR ( a.name = '%')))")
List<Company> findByCompanyName(@Param("name") String name);
@Query("SELECT a FROM Company a WHERE (:name is null or (LENGTH(:name) > 0 " +
" AND ((:option = 'yes' AND a.name = :name) or (:option = 'start' AND a.name LIKE CONCAT(:name,'%')) " +
" or (:option = 'end' AND a.name LIKE CONCAT('%',:name)) or (a.name LIKE CONCAT('%',:name,'%'))))) " +
" AND (:companyGroupId is null or a.companyGroupId = :companyGroupId) ORDER BY a.name")
Page<Company> findByParametersWeb(String name,Long companyGroupId, Pageable pageable);
List<Company> findAllByNameOrderByName();
}
Aucun commentaire:
Enregistrer un commentaire