I am trying to figure out mickito test for Named Jdbc Template but unable to do so. I did googling but did not find any accurate result. Below is example Code.
Student.class
#Data
public class Student {
private int id;
private String name;
private String address;
public Student(ResultSet rs) throws SQLException {
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
}
}
Student class takes ResultSet argument in constructor and mapped all column to variable .
StudentService.class
public class StudentService {
#Autowired
#Qualifier("namedJdbcTemplate")
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public Student gerStudent(String id) {
Student student;
String selectStudent = "select id , name ,address from student where id=:id";
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
mapSqlParameterSource.addValue(id, "id");
student = namedParameterJdbcTemplate.query(selectStudent, mapSqlParameterSource, resultSet -> {
Student response = new Student(resultSet);
return response;
});
return student;
}
}
Can anyone please help on Mockito Test for below line of code?
student = namedParameterJdbcTemplate.query(selectStudent, mapSqlParameterSource, resultSet -> {
Student response = new Student(resultSet);
return response;
});
Related
I am using spring JPA to attempt to write records to a postGres DB. At the time of the commit, I am getting the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "col_id" violates not-null constraint
Detail: Failing row contains (null, null, null, null, null)
I have the following repository interface:
public interface MyRepo extends JpaRepository <MyModel, String> {
}
, the following model class:
#Entity
#Validated
#Table(name = "my_table", schema="common")
public class MyModel {
#Id
#Column(name = "col_id")
private String id;
#Column(name = "second_col")
private String secCol;
#Column(name = "third_col")
private String thirdCol;
#Column(name = "fourth_col")
private String fourthCol;
#Column(name = "fifth_col")
private String fifthCol;
public MyModel() {
}
public MyModel(String id, String secCol, String thirdCol, String fourthCol, String fifthCol) {
this.id = id;
this.secCol = secCol;
this.thirdCol = thirdCol;
this.fourthCol = fourthCol;
this.fifthCol = fifthCol;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSecCol() {
return secCol;
}
public void setSecCol(String secCol) {
this.secCol = secCol;
}
public String getThirdCol() {
return thirdCol;
}
public void setThirdCol(String thirdCol) {
this.thirdCol = thirdCol;
}
public String getFourthCol() {
return fourthCol;
}
public void setFourthCol(String fourthCol) {
this.fourthCol = fourthCol;
}
public String getFifthCol() {
return fifthCol;
}
public void setFifthCol(String fifthCol) {
this.fifthCol = fifthCol;
}
}
, and the relevant part of the service class:
public MyModel myModel (MyModel myModel) {
MyModel mm = null;
try {
mm = myRepo.saveAndFlush(myModel);
} catch ( Exception e) {
e.printStackTrace();
}
return mm;
}
UPDATE:
I finally realized that my problem is due to a database trigger that auto-generates primary key against a complex business rule. Also, I assume I might need to use a custom save method rather than the default repo.saveAndFlush? I would be grateful for any ideas given new information. Thanks!
I reproduced the exact same code in a test project with Postgres and it worked well for me. You are absolutely correct that the values of the model class are not populated. You must share your controller also. It may really help me to help you if I can get a look where your service is being called from. Only that will help me to deduce why your model values are being passed as null in the service call.
Is it correct to write JUnit test case for Repository like this? Also while running it , Iam getting NullPointerException at line Mockito.when...
here is my test class:
#ContextConfiguration(locations = { "classpath*:resources/invoices-context.xml",
"classpath*:resources/invoices-int-schema.xml" })
public class RoomRepositoryTest {
#Autowired
RoomRepository roomRepository;
private RoomEntity roomEntity;
#Test
public void findRommByDateTest() throws ParseException {
String startDate = "27-07-2020";
sDate = new SimpleDateFormat("dd-mm-yyyy").parse(startDate);
String endDate = "28-07-2020";
eDate = new SimpleDateFormat("dd-mm-yyyy").parse(endDate);
String roomType = "SINGLE";
roomEntity = new RoomEntity();
roomEntity.setRoomId(1);
roomEntity.setRoomPrice(6000);
roomEntity.setRoomStatus("AVAILABLE");
roomEntity.setRoomType("SINGLE");
Mockito.when(
roomRepository.findRoomByDate(Mockito.any(Date.class), Mockito.any(Date.class), Mockito.anyString()))
.thenReturn(roomEntity.getRoomId());
int id = roomRepository.findRoomByDate(Mockito.any(Date.class), Mockito.any(Date.class), Mockito.anyString());
assertEquals(1, id);
}
}
Instead of mocking the database fetch function, you can just use the embedded database setup with some annotations. It helps us to test the query efficiently. If you are using an in-memory database(embedded) first you have to add (save) entry in the table. Then your query function should fetch the data. With the help of this you can easily debug the null pointer exceptions.
Eg:
#SpringBootTest
#AutoConfigureTestDatabase
#ContextConfiguration(locations = { "classpath*:resources/invoices-context.xml",
"classpath*:resources/invoices-int-schema.xml" })
public class RoomRepositoryTest {
#Autowired
RoomRepository roomRepository;
private RoomEntity roomEntity;
#Test
public void findRommByDateTest() throws ParseException {
String startDate = "27-07-2020";
sDate = new SimpleDateFormat("dd-mm-yyyy").parse(startDate);
String endDate = "28-07-2020";
eDate = new SimpleDateFormat("dd-mm-yyyy").parse(endDate);
String roomType = "SINGLE";
roomEntity = new RoomEntity();
roomEntity.setRoomId(1);
roomEntity.setRoomPrice(6000);
roomEntity.setRoomStatus("AVAILABLE");
roomEntity.setRoomType("SINGLE");
//adding data for testing
roomRepository.save(roomEntity)
//test the actual function
int id = roomRepository.findRoomByDate(sDate,eDate);
assertEquals(1, id);
}
Hi there im having some issues with MongoDb i have a CRUD and this is the code im using
First the POJO:
#Data
#Document(collection = "Informacion")
public class Informacion {
//Declaration code
public Informacion(Pais pais, Date fechaCreacion, String nombre, Boolean sexo,
Date fechaNacimiento, List<Preferencias> preferencias, String numTelefono, String usuario,
List<RedesSociales> redes, String contraseniaTW, String contraseniaFB, String contraseniaIG,
Grupo grupo, String paqChip, String email, String contraseniaMail, String fuente,
Date fechaRecarga) {
this.pais = pais;
this.fechaCreacion = fechaCreacion;
this.nombre = nombre;
this.sexo = sexo;
this.fechaNacimiento = fechaNacimiento;
this.preferencias = preferencias;
this.numTelefono = numTelefono;
this.usuario = usuario;
this.redes = redes;
this.contraseniaTW = contraseniaTW;
this.contraseniaFB = contraseniaFB;
this.contraseniaIG = contraseniaIG;
this.grupo = grupo;
this.paqChip = paqChip;
this.email = email;
this.contraseniaMail = contraseniaMail;
this.fuente = fuente;
this.fechaRecarga = fechaRecarga;
}
}
Now the DAO:
#Repository
public interface informacionRepo extends MongoRepository<Informacion,String> {
Informacion findByIdInformacion(String id);
}
And the controller:
#RestController
#RequestMapping("/Informacion")
public class InformacionControlador {
#Autowired
private informacionRepo informacioRepo;
public InformacionControlador(informacionRepo informacioRepo) {
this.informacioRepo = informacioRepo;
}
#GetMapping("/Listar")
public List<Informacion> getAll(){
List<Informacion> info = this.informacioRepo.findAll();
System.out.println(info.isEmpty());
return info;
}
#PutMapping
public void insert(#RequestBody Informacion informacion){
this.informacioRepo.insert(informacion);
}
public void update(#RequestBody Informacion informacion){
this.informacioRepo.save(informacion);
}
#DeleteMapping("/Listar/{id}")
public void delete(#PathVariable("id") String id){
this.informacioRepo.deleteById(id);
}
#GetMapping("/Listar/{id}")
public Informacion getById(#PathVariable("id") String id){
Informacion info = this.informacioRepo.findByIdInformacion(id);
return info;
}
}
Im using POSTMAN to test the methods above but im getting empty answers, the data is already set on the Database, im using a method call seeder that fills the data also y check it with robo mongo and the data is there but still getting empty answers also when i try the insert method i get 403 error.
Thanks for your help
This is the answer seen from the web browser
The problem was that im using the annotation #Data from lombok but i didnt enable annotation processing in the IDE just enable it and works :D
Hi i am new for WebServices and In my My-Sql Database I have student table with some columns those are "user_id", and "name" and "marks"
I want to update one row based on userId for this i wrote below code but i am getting exception like below can some one help me please
Controller [com.ensis.sample.controller.SampleController]
Method [public com.ensis.sample.model.StatusObject com.ensis.sample.controller.SampleController.updateStudentListById(int)]
org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'userId' is not present
controller:-
#RequestMapping(value="/update",method=RequestMethod.POST,produces={"application/json"})
#ResponseBody
public StatusObject updateStudentListById(#RequestParam int userId){
return userService.updateStudentDetailsById(userId);
}
UserService:-
#Transactional
public StatusObject updateStudentDetailsById(int id){
Users users = usersdao.updateStudentDetailsById(id);
if(users!=null){
users.setName("Sample");
users.setMarks(99.99);
}
StatusObject statusObject = new StatusObject();
boolean status = usersdao.updateUser(users);
if(status==true){
statusObject.setStatus(false);
statusObject.setMessage("Success");
return statusObject;
}else{
statusObject.setStatus(true);
statusObject.setMessage("Failure");
return statusObject;
}
}
UserDao:-
public Users updateStudentDetailsById(int userId){
System.out.println("UserId is=====>"+userId);
String hql = "FROM Users s WHERE " + "s.user_id = :userId";
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hql);
query.setParameter("user_id", userId);
List<?>list = query.list();
Iterator<?>itr = list.iterator();
if(itr.hasNext()){
Users users = (Users)itr.next();
return users;
}
session.flush();
session.clear();
return null;
}
Users:-
#Entity
#Table(name = "student")
public class Users {
#Id
private int user_id;
private String name;
private int rank;
private double marks;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public double getMarks() {
return marks;
}
public void setMarks(double marks) {
this.marks = marks;
}
#Krish, when you are posting something, you usually use Spring's #RequestBodyas seen below:
#RequestMapping(value="/update",method=RequestMethod.POST,produces={"application/json"})
#ResponseBody
public StatusObject updateStudentListById(#RequestBody User user){
return userService.updateStudentDetailsById(userId);
}
You need to pass the JSON object to this controller method. Spring will deserialize the JSON for you.
When you say #RequestParam, it expects to find the request parameters like
/update?userId=1
PS: It is not good practice to send just the ID to update a resource.
Are you using it as a RestController.The excecption is coming from the controller as it expects a parameter from the client.Please verify if you are passing the userID in the pathParam.
I have created a database called student base on the tutorial provided by tutorials point PDF, they have covered how to map the form and insert values in to the database using controllers, but they have not explained how to display the data from the database on to the webpage.
My code to list all students.
#Override
public List<Student> listStudents() {
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
How to call this from my controller in spring and return the list to my webpage.
My contoller is given below
#Controller
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student()
{
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student, ModelMap model)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
studentJDBCTemplate.create(student.getName(), student.getAge());
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("msg", "Student Enrolled");
return "result";
}
// How to write the listing controller?
}
From the details you provide ,
public String ListStudents(ModelMap model)
{
List<Student> list= YourServiceClassObj.listStudents();
model.addAttribute("result", list);
return "View Name here";
}
public class AccountDAO {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public Account getAll(String user, String pass) {
String query = "SELECT * FROM dbo.USERR WHERE username=? AND password =?";
try {
conn = new DBContext().getConnection();
ps = conn.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
while (rs.next()) {
return new Account(rs.getString(1),
rs.getString(2),
rs.getString(3));
}
} catch (Exception e) {
}
return null;
}
}
your controller and service methods should be like this .and then in the view use the controller returned attribute students.
#Controller
#RequestMapping(value = "/students", method = RequestMethod.GET)
public String students(ModelMap model)
{
List<Student> students= studentService.getStudents();
model.addAttribute("students", students);
return "student/studentList.html";
}
Service :
public interface StudentService {
List<Student> getStudents();
}
#Service
public class StudentServiceImpl implements StudentService {
#Override
public List<Student> getStudents() {
return studentRepository.findAll();
}