Skip to content

Instantly share code, notes, and snippets.

//Given an array arr[] of N elements, the task is to write a function to search a given element x in arr[].
public class LinearSearch {
public static int search(int arr[], int x) {
int n= arr.length;
for(int i=0; i<n; i++){
if (arr[i] == x) return i;
}
return -1;
@ExtendWith(MockitoExtension.class)
class UserDataServiceImplTest {
@Mock
private UsersRepository userRepository;
@InjectMocks
private UserDataServiceImpl userService;
@BeforeEach
void setUp() {
@AllArgsConstructor
@Service
public class UserDataServiceImpl implements UserDataService {
private final UsersRepository usersRepository;
@Override
public Page getUsers(Specification specification, PageRequest pageRequest) {
return usersRepository.findAll(specification,pageRequest);
}
public class UserPredicate implements Specification<Users> {
private SearchCriteria criteria;
public UserPredicate(SearchCriteria criteria) {
this.criteria = criteria;
}
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> cq, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(">")) {
@Repository
public interface UsersRepository extends JpaRepository<Users, Integer>, JpaSpecificationExecutor<Users> {
Boolean selectExistsEmail(String email);
}
@Test
void deleteUsers() {
Integer id = 1;
given(userRepository.existsById(id)).willReturn(true);
userService.deleteUser(id);
verify(userRepository).deleteById(1);
}
@Test
public void deleteUser(Integer id) {
if(!usersRepository.existsById(id)) {
throw new UserNotFoundException(
"User with id " + id + " does not exists");
}
usersRepository.deleteById(id);
}
@Test
void addUsers() {
//create a user in h2
Users users = new Users(1, "mercy", "[email protected]");
userService.addUsers(users);
// captures the actual value of the student passed to the save method
ArgumentCaptor<Users> studentArgumentCaptor = ArgumentCaptor.forClass(Users.class);
verify(userRepository).save(studentArgumentCaptor.capture());
@Override
public Users addUsers(Users user) {
Boolean existsEmail = usersRepository.selectExistsEmail(user.getEmail());
if (existsEmail) {
throw new BadRequestException(
"Email " + user.getEmail() + " taken");
}
return usersRepository.save(user);
@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {
@Mock
private UsersRepository userRepository;
private UserServiceImpl userService;
@BeforeEach
void setUp() {
//initialize mock