Test cases for controller class - spring-boot

how to write test case for this getmapping returning ModelAndView and postmapping?
#GetMapping("/login")
ModelAndView custLoginPage() {
ModelAndView mView = new ModelAndView();
mView.setViewName("userLogin.jsp");
return mView;
}
#PostMapping("/validate")
ModelAndView validate(#RequestParam("userEmail") String uEmail, #RequestParam("userPass") String uPass) {
Customer c = custserv.validate(uEmail, uPass);
ModelAndView mView = new ModelAndView();
if(c!=null) {
cust = c;
bkcntl.setUid(c);
mView.setViewName("redirect:/Movies2");
}
else {
mView.setViewName("redirect:/userloginfail");
}
return mView;
}
testcases for the those two mappings

Related

I insert a null column and in the next I save the data

because when I make a record in my form to the database first I register a null column and after the value that I insert, I am using spring
#RequestMapping("/listaPalabras")
public ModelAndView listaPalabras(Palabras uploadItem, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("listaPalabras");
List<Palabras> list = palService.listPalabras();
return new ModelAndView("listaPalabras", "list", list);
}
#RequestMapping(value = "/agregarPalabras", method = RequestMethod.GET)
public String productCreate(#ModelAttribute("palabra") Palabras palabras) {
palService.saveOrUpdate(palabras);
return "agregarPalabras";
}
this is result

Spring #SessionAttributes not working

My Controller class
#Controller
#SessionAttributes("basschoolsform")
public class SchoolStudentsConfirmationContrl
{
Below method accepts ac_year and gets data accordingly and redirects to page showreport
#RequestMapping(value="/SchoolStudentConfirmation.getData",method=RequestMethod.GET)
public ModelAndView BASyearWiseReport(#ModelAttribute BASSchoolsForm basschoolsform,HttpServletRequest request)
{
ModelAndView mav=new ModelAndView();
try
{
List<Object[]> result=schoolstdconfirmservice.BASyearWiseReport(request,basschoolsform);
PageHeading = "BAS Students Confirmation for the Academic Year:"+ basschoolsform.getAc_year()
if(!result.isEmpty())
{
mav.addObject("result",result);
}
else
{
mav.addObject("msg","NO Data Found");
}
mav.setViewName("showreportwithmenu");
}
catch(Exception e)
{
e.printStackTrace();
}
mav.addObject("basschoolsform",basschoolsform);
return mav;
}
This Method also uses ac_year and gets data and redirects to studentstatusedit
#RequestMapping(value="/SchoolStudentConfirmation.ConfirmStudentByDO",method=RequestMethod.GET)
public ModelAndView ConfirmStudentByDO(#ModelAttribute BASSchoolsForm basschoolsform,HttpServletRequest request)
{
ModelAndView mav=new ModelAndView();
System.out.println(basschoolsform.getAc_year()+" later value");
List<BASSchoolsForm> studentdata=schoolstdconfirmservice.ConfirmStudentByDO(basschoolsform,request);
if(studentdata != null && studentdata.size() > 0)
{
mav.addObject("PageHeading","Academic Year:"+request.getParameter("ac_year")+" School: "+request.getParameter("school"));
mav.addObject("studentdata",studentdata);
mav.addObject("schooltype",request.getParameter("school").split("-")[2]);
request.setAttribute("school",request.getParameter("school"));
}
else
{
mav.addObject("msg","All Applications are Confirmed");
mav.addObject("showyear","showyear");
}
mav.setViewName("studentstatusedit");
return mav;
}
Though I have added sessionAttribute i get ac_year as null in next method.
Please Tell me where im being wrong
First you need to initialize ModelAttribute and use the ModelAttribute name in the method parameter
#Controller
#SessionAttributes("basschoolsform")
public class SchoolStudentsConfirmationContrl
{
#ModelAttribute("basschoolsform")
public BASSchoolsForm populate(){
return new BASSchoolsForm();
}
................
public ModelAndView ConfirmStudentByDO(#ModelAttribute("basschoolsform") BASSchoolsForm basschoolsform,HttpServletRequest request)
{

Render a view based on the conditional statement in Spring

I am kind of new to Spring. I am trying to render a view based on the the value returned from DBDAOImplementation class using a conditional if statement inside processController. I am trying to return successuseraddstatus jsp file for success scenarios and faileduseraddstatus jsp file for failed scenarios.
ProcessController.java:
#RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Process process,ModelMap model) {
model.addAttribute("fname", process.getFname());
model.addAttribute("lname", process.getLname());
model.addAttribute("email", process.getEmail());
model.addAttribute("phone", process.getPhone());
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
DBDAOImp dbd =
(DBDAOImp)context.getBean("JDBCTemplate");
dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone());
if (true){ //This is where I am having trouble
return "successuseraddstatus";
}
return "faileduseraddstatus";
}
DBDAOImplementation.java:
#Override
public Boolean createuser(String fname, String lname, String email, String phone) {
isExists(email);
if (isExists==false){
String SQL = "insert into USERS (user_id,f_name,l_name,creation_date,email,phone) values (seq_users.nextval,?,?,sysdate,?,?)";
jdbcTemplateObject.update( SQL, fname,lname,email,phone);
System.out.println("Created Record");
return true;
} else {
return false;
}
}
Below if condition works. But I am not too sure if this is the right approach.
ProcessController.java:
#RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Process process,ModelMap model) {
model.addAttribute("fname", process.getFname());
model.addAttribute("lname", process.getLname());
model.addAttribute("email", process.getEmail());
model.addAttribute("phone", process.getPhone());
DBDAOImp dbd =
(DBDAOImp)context.getBean("JDBCTemplate");
if (dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone())){
return "useraddstatus";
} else {
return "faileduseraddstatus";
}
}

How to list data from database in a web page in spring framework

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();
}

Spring : timely/late binding of #ModelAttribute

I'm using the following code to bind the users to the model [to be used in the view/jsp]:
#ModelAttribute("users")
public Collection<User> populateUsers() {
return userService.findAllUsers();
}
But sometimes I just need to load few users with a particular Role, which I'm trying by using the following code:
int role = 2; //this is being set in a Controller within a method #RequestMapping(method = RequestMethod.GET) public String list(
#ModelAttribute("users")
public Collection<User> populateUsers() {
if(role == 2)
return userService.findAllUsersByRole(role);
else
return userService.findAllUsers();
}
but the populateUsers is always called at the start of the controller, before the role is set in list method, Could you please help me on how to set the users [something like late binding]
Regards
-- adding code
#Controller
#RequestMapping("/users")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(method = RequestMethod.POST)
public String create(#Valid User user, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("user", user);
addDateTimeFormatPatterns(uiModel);
return "users/create";
}
uiModel.asMap().clear();
userService.saveUser(user);
return "redirect:/users/"
+ encodeUrlPathSegment(user.getId().toString(),
httpServletRequest);
}
#RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model uiModel) {
uiModel.addAttribute("user", new User());
addDateTimeFormatPatterns(uiModel);
return "users/create";
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String show(#PathVariable("id") Long id, Model uiModel) {
addDateTimeFormatPatterns(uiModel);
uiModel.addAttribute("user", userService.findUser(id));
return "users/show";
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
public String updateForm(#PathVariable("id") Long id, Model uiModel) {
uiModel.addAttribute("user", userService.findUser(id));
addDateTimeFormatPatterns(uiModel);
return "users/update";
}
#ModelAttribute("users")
public Collection<User> populateUsers() {
return userService.findAllUsers();
}
#ModelAttribute("userroles")
public Collection<UserRole> populateUserRoles() {
return Arrays.asList(UserRole.class.getEnumConstants());
}
void addDateTimeFormatPatterns(Model uiModel) {
uiModel.addAttribute(
"user_modified_date_format",
DateTimeFormat.patternForStyle("M-",
LocaleContextHolder.getLocale()));
}
}
#PathVariable("id") Long id is the ID I require in populateUsers, hope it is clear.
If role is in the current request, this method binding role to variable role.
#ModelAttribute("users")
public Collection<User> populateUsers(#RequestParam(required=false) Integer role) {
if(role != null && role == 2)
return userService.findAllUsersByRole(role);
else
return userService.findAllUsers();
}
Setting the model attribute in the required method has solved my issue:
model.addAttribute("users", return userService.findAllUsersByRole(role));
Thanks!

Resources