我正在尝试在我的serviceinpl类中测试save方法。它将页作为返回类型。测试成功了,但我写了一些错误,因为它成功的所有情况下,通常不应该请看我的代码如下。
服务类实现
@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);
}
}
测试服务类
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());
}
}
最后是我的公司存储库
@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();
}
1条答案
按热度按时间h79rfbju1#
所以您想在这里区分单元测试和集成或组件测试。您的测试可以作为一个单元测试,它只测试您的服务层的功能,与其他所有功能隔离开来。
这也是为什么要模拟存储库层,使其独立于数据库。
与此相反,集成和组件测试将测试整个应用程序堆栈。
为此,必须运行spring引导环境,因此必须使用
@ExtendWith(SpringExtension.class)
.对于这些类型的测试,您需要一个活动的db,因此通常使用h2数据库进行测试,在测试之前填充数据。看看这个和这个。
在测试本身中,要么注入服务并从那里进行测试,要么使用
RestTemplate
.