Mockito Test fails when service comes to stream.map.collect - spring

This is the method in my service. I get the Exception when .stream.map.collect
#Override
public GameDto save(GameRequestDto gameRequestDto) {
Optional<Game> gameOptional = gameRepository.findByTitleAndStudio(gameRequestDto.getTitle(),
gameRequestDto.getStudio());
if (gameOptional.isPresent()) {
throw new InvalidRequestException("Game with title: " + gameRequestDto.getTitle() +
" and studio: " + gameRequestDto.getStudio() + " already exists.");
}
Game gameToBeSaved = buildGameToBeSaved(gameRequestDto);
Game savedGame = gameRepository.save(gameToBeSaved);
GameDto gameDto = gameMapper.gameToGameDto(savedGame);
gameDto.setGameGenres(savedGame.getGenres().stream()
.map(Genre::getGenreName)
.collect(Collectors.toCollection(HashSet::new)));
return gameDto;
}
This is my Test
#InjectMocks
GameServiceImpl gameService;
#Mock
GameRepository gameRepository;
#Mock
GenreRepository genreRepository;
#Test
public void saveGameTest() throws Exception {
Set genres = new HashSet<>();
genres.add("Role Playing");
Game savedGame = buildGame(genres);
Mockito.when(gameRepository.save(any(Game.class))).thenReturn(savedGame);
gameService.save(buildGameRequestDto(genres));
Mockito.verify(genreRepository, Mockito.times(4));
Mockito.verify(gameRepository, Mockito.times(1));
}
And this is the Exception
java.lang.ClassCastException: class java.lang.String cannot be cast to class com.home.myproject.entities.Genre (java.lang.String is in module java.base of loader 'bootstrap'; com.home.myproject.entities.Genre is in unnamed module of loader 'app')

Related

java.lang.IllegalArgumentException: Could not find field 'isBoolean' of type [class java.lang.Boolean] on target object

When I run test then it failed at this point ReflectionTestUtils.setField(service, SeRepositoryImpl.class, "isBoolean",true,Boolean.class) complains about Could not find field 'isBoolean' of type not found. Error trace as below.
I am not sure why because my repositoryImpl class has isBoolean variable defined.
java.lang.IllegalArgumentException: Could not find field 'isBoolean' of type [class java.lang.Boolean] on target object [lautomation.repository.impl.SaRepositoryImpl#4a178d1e] or target class [lautomation.repository.impl.SaRepositoryImpl]
at org.springframework.test.util.ReflectionTestUtils.setField(ReflectionTestUtils.java:175)
test class looks like
#MockBean(name = "seRepository")
PolicyRepository seRepository;
#InjectMocks
private SeRepositoryImpl service;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testUpdateStatus() throws Exception{
ReflectionTestUtils.setField(service, SeRepositoryImpl.class, "isBoolean",true,Boolean.class);
List<Policy> policies = Arrays.asList(new Policy[] {new Policy() });
service.updateIssuedStatus(Mockito.any(Policy.class));
Mockito.verify(seRepository, Mockito.times(1)).updateIssuedStatus(Mockito.any(Policy.class));
}
}
Respository implementation class SeRepositoryImpl has isBoolean variable defined
#Repository("seRepository")
#Log4j
public class SeRepositoryImpl implements PolicyRepository {
#Value("${change-db}")
private boolean isBoolean;
#Autowired
#Qualifier("jdbcDbName")
private NamedParameterJdbcTemplate jdbcTemplate;
#Override
public void updateIssuedStatus(final Policy policy) {
if(!isBoolean) {
log.warn("isBoolean is set to false - skipping db write.");
return;
}
final HashMap<String, String> params = new HashMap<>();
params.put("issued",
new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
params.put("id", Integer.toString(policy.getId()));
jdbcTemplate.update(updateIssuedStatus, params);
String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
log.info("params:"+Integer.toString(policy.getId())+" Date:"+currDate);
final String sql = "call usp_updateDatabase(:policy,:currDate)";
MapSqlParameterSource value = new MapSqlParameterSource();
value.addValue("id",Integer.toString(policy.getId()));
value.addValue("stop_dt",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
jdbcTemplate.update(sql, value);
}
}

Take the sum of the query result as separate data

Etity
#Entity
public class DateFMail {
#Id
private double balance;
public DateFMail() {
}
public DateFMail(double balance) {this.balance = balance;}
public DateFMail(DateFMail dateFMail) {
}
public double getBalance() { return balance;}
#Override
public String toString() {
return "DateFMail{" +
"balance=" + balance +
'}';
}
}
Service
public interface DateFMailService {
List<DateFMail> findAll();
}
Impl
#Service
public class DateFMailServiceImpl implements DateFMailService {
#Autowired
private DateFMailRepository mailRepository;
#Override
public List<DateFMail> findAll() {
return mailRepository.findAll();
}
}
Repository
#Repository
public interface DateFMailRepository extends JpaRepository<DateFMail, Long> {
#Query(value = "SELECT SUM(balance) \n" +
" FROM agents", nativeQuery = true)
List<DateFMail> findAll();
}
Mail Seder
#Service
public class EmailDos {
#Autowired
private JavaMailSender mailSender;
private DateFMailRepository mailRepository;
String fileDate1 = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
LocalDate today = LocalDate.now();
String fileDate = (today.minusDays(1)).format(DateTimeFormatter.ofPattern("dd MMM"));
String fileDate2 = (today.minusMonths(1)).format(DateTimeFormatter.ofPattern("MMM"));
public void sendMailSum(String from, String to, String subject, String body, String fileToAttach) throws SQLException {
List<DateFMail> list = new ArrayList<>(mailRepository.findAll());
List<DateFMail> list1 = list.stream()
.map(DateFMail::new)
.collect(Collectors.toList());
System.out.println("sending email...................");
System.out.println(list1);
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
mimeMessage.setText(body);
FileSystemResource file = new FileSystemResource(new File("C:...xlsx"));
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("SomeAddress#gmail.com");
helper.setTo(InternetAddress.parse("SomeAddress#gmail.com"));
helper.setText("Good day!\nIn attachment payments for " + fileDate + " с 12.00-00.00" + "\nAmount for " + fileDate1 + list1);
helper.addAttachment("...xlsx", file);
mailSender.send(mimeMessage);
System.out.println("email Fab was successfully sent.....");
}
};
try {
mailSender.send(preparator);
} catch (MailException ex) {
System.err.println(ex.getMessage());
}
}
}
Controller
#Component
public class DateFMailController {
#Autowired
private DateFMailService mailService;
public void saveSum() throws IOException {
saveExcel(mailService.findAll(), "....xlsx");
}
private void saveExcel(List<DateFMail> list, String fileName) throws IOException {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("ECards");
sheet.autoSizeColumn(0);
Row header = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 10);
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("Sum");
headerCell.setCellStyle(headerStyle);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
int ix_row=2;
for (DateFMail dateFMail : list) {
Row row = sheet.createRow(ix_row);
Cell cell = row.createCell(0);
cell.setCellValue(dateFMail.getBalance());
cell.setCellStyle(style);
ix_row++;
}
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
workbook.close();
}
}
Save Runer
#Component
public class SaveCardsStartupRunner implements ApplicationRunner {
#Autowired
private ECardController eCardController;
private DateFMailController controller;
// #Autowired
// private EmailDos emailDos;
String fileDate1 = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
LocalDate today = LocalDate.now();
String fileDate = (today.minusDays(1)).format(DateTimeFormatter.ofPattern("dd MMM"));
String fileDate2 = (today.minusMonths(1)).format(DateTimeFormatter.ofPattern("MMM"));
#Override
public void run(ApplicationArguments args) throws Exception {
eCardController.saveCards();
controller.saveSum();
}
}
I have corrected my question. I've pasted all the code here that pertains to my question. For starters, I would like to simply output the Query result of the repository to the console. But in the form that I just posted here, I get a NullPointerException error and says that in a part of the code: controller.saveSum (); - controller = null.
Create a PaymentService class which should contain the method getTotalPayment. Inject this class in EmailSend (tip: please change this class name from EmailSend to EmailSender as class names should be noun) class. And then in PaymentService Class you should interact Data Repository class. Call this getTotalPayment method from the EmailSend class.

#Autowired entity is getting null

#Component
public class TempTry implements CommandLineRunner{
#Autowired
TokenRepository tkeRepo;
#Parameter(names = { "--email", "-e" })
String email;
static final Logger logger = LoggerFactory.getLogger(TempTry.class);
#Override
public void run(String... args) throws Exception {
logger.info("ApplicationStartupRunner run method Started !!");
TempTry main = new TempTry();
JCommander.newBuilder().addObject(main).build().parse(args);
main.runtask();
}
public void runtask() {
LocalDateTime expiryTime = LocalDateTime.now().plusDays(1);
String uuid = UUID.randomUUID().toString();
TokenEntity tknEntity = new TokenEntity();
tknEntity.setEmailId(email);
tknEntity.setExpiryTime(DateUtils.asDate(expiryTime));
tknEntity.setStatus(ResetPasswordStatus.ACTIVE);
tknEntity.setToken(uuid);
tkeRepo.save(tknEntity);
String fromString = UUID.nameUUIDFromBytes("SomeString".getBytes()).toString();
System.out.println("For email " + mail + " UUID=" + uuid + " is stored at time " + new Date());
System.out.println("UUID generated from String is " + fromString);
}
}
I set run configuration as -e dhanrajtijare#gmail.com ..getting email value as expected.
My problem here is at line tkeRepo.save(tknEntity); tkeRepo is null
Here
TempTry main = new TempTry();
How do you expect #Autowire to work if you are creating instance yoursefl?
Your current instance seems to be in app context by that point, so
#Override
public void run(String... args) throws Exception {
logger.info("ApplicationStartupRunner run method Started !!");
JCommander.newBuilder().addObject(this).build().parse(args);
runtask();
}
I put aside the fact that IMHO its just bad to mix JCommander with Spring CLI - use either one or another.

CrudRepository Unsatisfied dependency expressed through field folioRepository

I am getting error Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getFolioService': Unsatisfied dependency expressed through field 'folioRepository': No qualifying bean of type [a.b.c.repository.FolioRepository]
I am running Junit test case for my service, which save document in couchbase.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FolioServiceTest {
#Autowired
private FolioService folioService;
#Test
public void testAddFolioTransaction() {
Folios folios = new Folios();
folios.setUiid("user123");
List<Order> orders = new ArrayList<Order>();
Order order = new Order();
order.set__type("type1");
order.set__version("version1");
order.setCreatedDate("09/02/2016");
order.setCreatedUser("test user");
OrderPayload orderPayload = new OrderPayload();
orderPayload.set__type("type payload type");
orderPayload.set__version("version payload type");
order.setOrderPayload(orderPayload);
orders.add(order);
folios.getOrder().addAll(orders);
boolean flag= folioService.addFolioTransaction(folios);
assertTrue(flag == true);
}
#Configuration
public class AppConfig {
#Bean
public FolioService getFolioService() {
return new FolioService();
}
}
}
#Service
public class FolioService {
private final static Logger LOGGER = LoggerFactory.getLogger(FolioService.class);
#Autowired
FolioRepository folioRepository;
/**
* Method will save the folio to the couchbase
*
* #param folios
*/
public boolean addFolioTransaction(Folios folios){
LOGGER.debug("Adding transaction details to folio.");
Folios newFolio = folioRepository.save(folios);
if (newFolio != null) {
return true;
}
return false;
}
public Folios getFolioDetailsByUiid(String uiid){
LOGGER.debug("Get folio details by uiid.");
Folios folios = folioRepository.findOne(uiid);
return folios;
}
}
#Repository
public interface FolioRepository extends CrudRepository{
}

java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;

I am trying to access list of friends of given username using hibernate. Here is my Service class in which fetchListOfFriends function is used to convert the generic list to an Arraylist of type of FriendsDetails.
#Service
#Transactional
public class DetailsServiceImpl implements DetailsService {
#Autowired
private DetailsDao detailsDao;
#Override
public List<FriendsDetails> fetchListOfFriends(String name) {
#SuppressWarnings("rawtypes")
List listOfFriends=detailsDao.fetchListOfFriends(name);
List<FriendsDetails> friendList= fetchListOfFriendss(listOfFriends);
if(listOfFriends==null){
System.out.println("Empty and null list");
}
System.out.println("size of friendList" + listOfFriends.size());
return friendList;
}
private List<FriendsDetails> fetchListOfFriendss(#SuppressWarnings("rawtypes") List genericList) {
#SuppressWarnings("unchecked")
List<Object> result = (List<Object>) genericList;
Iterator<Object> itr = result.iterator();
List<FriendsDetails> listOfFriend= new ArrayList<FriendsDetails>();
while(itr.hasNext()){
Object[] obj = (Object[]) itr.next();
System.out.println(obj.toString());
String userName = String.valueOf(obj[0]);
FriendsDetails obj1= new FriendsDetails();
obj1.setFriendName(userName);
listOfFriend.add(obj1);
}
return listOfFriend;
}
DetailsDaoImpl.java
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("rawtypes")
#Override
public List fetchListOfFriends(String name) {
Session session=sessionFactory.getCurrentSession();
String queryToFetchFriends="Select name,presenceStatus from UserPresence where name in (Select friendName from Friends where name='"+name+"')";
List listOfFriends=session.createSQLQuery(queryToFetchFriends).list();
return listOfFriends;
}
Logs.txt
May 22, 2016 1:24:11 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [springmvc] in context with path [/Testing] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;] with root cause
java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;
at com.tcs.Service.FriendServiceImpl.searchFriend(FriendServiceImpl.java:61)
at com.tcs.Service.FriendServiceImpl.searchFriend(FriendServiceImpl.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Everything should work correctly.
The problem, obviously, that List listOfFriends is List<String>, not List<Object[]>. It is strange, because of Select name,presenceStatus from UserPresence should return List<Object[]>.
Maybe Spring set an incorrect implementation of #Autowired
private DetailsDao detailsDao;.
Try this code. This should work for List<String>
private List<FriendsDetails> fetchListOfFriendss(List<?> genericList) {
Iterator<?> itr = genericList.iterator();
List<FriendsDetails> listOfFriend = new ArrayList<FriendsDetails>();
while (itr.hasNext()) {
Object obj = itr.next();
String userName = String.valueOf(obj);
System.out.println(userName);
FriendsDetails obj1 = new FriendsDetails();
obj1.setFriendName(userName);
listOfFriend.add(obj1);
}
return listOfFriend;
}

Resources