I'm trying to use the methods that I have in a DAO interface. When i'm calling there in a Servlet, I have no problems, for example, if I test
#WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
//etc
#EJB
InterfacesDao dao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//dao.getUsers(); //works well
//System.out.println(dao); //will print the dao object correctly
Boolean logged = dao.login("myLogin","mystrongpassword"); //works
request.setAttribute("logged",logged);
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
}
//etc
}
But I want to use ajax and so pass by a WebServices.
I can test
#WebService
#Path("/users")
public class UserService {
#POST
#Path("/login")
#Produces("application/json")
public String login(#FormParam("login") String login, #FormParam("pwd") String mdp) {
return "Hello World" + login;
}
}
If I go to http://[...]/rest/users/login with an json object which contains a login and a pwd, I get Hello World theloginientered
But I need to use EJB
#WebService
#Path("/users")
public class UserService {
#EJB
InterfacesDao dao;
#POST
#Path("/login")
#Produces("application/json")
public String login(#FormParam("login") String login, #FormParam("pwd") String mdp) {
//System.out.println(dao); //dao null ?
//dao.getUsers(); //erros because dao null
Boolean logged = dao.login(login,pwd); //doesn't work
//I not arrive till here because NullPointerException error
return "Hello World" + login;
}
}
I tried to instance by passing the reference of the dao in my servlet to my Web Service, but doesn't work
I tried to have just 1 EJB in my WebService, init in constructor, and get it from my Servlet by a getter, but again null
I think I forgot a config for the EJB dependency injection but in my Servlet I do no more less.
Import for the web services
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.servlet.annotation.WebServlet;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.supinfo.interfaces.InterfacesDao;
import com.supinfo.servlet.Index;
Import for the Servlet
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.supinfo.interfaces.InterfacesDao;
Interfaces DAO Web side and EJB side
package com.supinfo.interfaces;
import java.util.List;
import javax.ejb.Remote;
import com.supinfo.entity.User;
#Remote
public interface InterfacesDao {
public boolean login(String login, String mdp);
public boolean signin(String login, String mdp);
public List<User> getUsers();
}
The Implementation
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.supinfo.database.PersistenceManager;
import com.supinfo.entity.User;
import com.supinfo.interfaces.InterfacesDao;
#Stateless
public class InterfaceDaoImpl implements InterfacesDao{
#Override
public List<User> getUsers() {
EntityManager em = PersistenceManager.getEntityManager();
Query query = (Query) em.createQuery("Select u FROM User u ");
List<User> persons = query.getResultList();
return persons;
}
#Override
public boolean login(String login, String mdp) {
EntityManager em = PersistenceManager.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> person = query.from(User.class);
query.where(cb.equal(person.get("login"), login)).where(cb.equal(person.get("mdp"), mdp));
List<User> persons = em.createQuery(query).getResultList();
//Boolean isEmpty = persons.isEmpty();
//return !(isEmpty == null ? false : isEmpty);
return !persons.isEmpty();
}
Thanks for reading
The import statements are not included in the sample code, but I assume that you are trying to use JAX-RS and not a WebService. In that case, you should delete the #WebService annotation.
Depending on the server (and version) you are using the injection of the dao will not instantly work using #EJB as annotation. You can however transform the JAX-RS endpoint to a #Stateless bean, that should take care of your injection problem.
In short use:
#Stateless
#Path("/users")
public class UserService {
#EJB // #Inject is also an option
InterfacesDao dao;
You may also want to use the newer #Inject annotation instead of #EJB.
Related
hi i am learning Java and Spring Framework, i don't even consider myself beginner. The other day i found great study material "Spring-Boot Masterclass". I am learning from this source, first part was about making simple REST API CRUD application with custom methods, custom exceptions, by using MySQL database. I've learned a lot from this source, and everything went smooth, i understood everything till now, i am at testing repository, service and controller layers. I managed to create tests for CRUD methods + few custom methods for all 3 layers, and all tests passed with green result in Eclipse, i just stopped at void deleteMinisterstvo() method. Question is in Controller Layer above mentioned method in comment, but i'll share it here too, because i am getting lost:
HOW is this working, when i create database record with id=15, then delete ID=4 from endPoint for ID= 55, and TEST passes? Which one is being deleted then?
Maybe i did not even write method as it should be written, so i would like to ask you, experienced developers on your opinion, idea, maybe explanation. Thanks
*Note1: I started this thread with Hi, i... but it somehow did not save, so i tried to edit and even edit does not give Hi there. Sorry for that.
*Note2: I removed all other methods (commented them out) from Repository, Service and Controller layers for focusing only at deleteMethod. I thought, that this test should not pass, but throw error:
Project
MinisterstvoRepository
package com.Ministerstvo.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.Ministerstvo.Model.Ministerstvo;
#Repository
public interface MinisterstvoRepository extends JpaRepository<Ministerstvo, Long>{
}
MinisterstvoService
package com.Ministerstvo.Service;
import java.util.List;
import com.Ministerstvo.Exceptions.MinisterstvoNotFoundException;
import com.Ministerstvo.Model.Ministerstvo;
public interface MinisterstvoService {
void odstranMinisterstvo(Long id) throws MinisterstvoNotFoundException;
}
MinisterstvoServiceImpl
package com.Ministerstvo.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Ministerstvo.Controller.MinisterstvoController;
import com.Ministerstvo.Exceptions.MinisterstvoNotFoundException;
import com.Ministerstvo.Model.Ministerstvo;
import com.Ministerstvo.Repository.MinisterstvoRepository;
import lombok.AllArgsConstructor;
import lombok.Data;
#Service
#Data
#AllArgsConstructor
public class MinisterstvoServiceImpl implements MinisterstvoService {
#Autowired
private final MinisterstvoRepository ministerstvoRepository;
private final Logger LOGGER = LoggerFactory.getLogger(MinisterstvoController.class);
#Override
public void odstranMinisterstvo(Long id) throws MinisterstvoNotFoundException {
LOGGER.info("Metoda odstranMinisterstvo() v MinisterstvoServiceImpl");
Optional<Ministerstvo> ministerstvo = ministerstvoRepository.findById(id);
if(!ministerstvo.isPresent()) {
throw new MinisterstvoNotFoundException("Ministerstvo so zadanym ID neexistuje...");
}
ministerstvoRepository.deleteById(id);
}
}
MinisterstvoController
package com.Ministerstvo.Controller;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.Ministerstvo.Exceptions.MinisterstvoNotFoundException;
import com.Ministerstvo.Model.Ministerstvo;
import com.Ministerstvo.Service.MinisterstvoService;
import lombok.AllArgsConstructor;
import lombok.Data;
#RestController
#Data
#AllArgsConstructor
public class MinisterstvoController {
#Autowired
private final MinisterstvoService ministerstvoService;
private final Logger LOGGER = LoggerFactory.getLogger(MinisterstvoController.class);
// API - DELETE
#DeleteMapping("/ministerstva/{id}")
public ResponseEntity<String> odstranMinisterstvo(#PathVariable("id") Long id) throws MinisterstvoNotFoundException {
LOGGER.info("Metoda odstranMinisterstvo() v MinisterstvoController");
ministerstvoService.odstranMinisterstvo(id);
return new ResponseEntity<String>("Uspesne odstranene ministerstvo", HttpStatus.OK);
}
}
MinisterstvoControllerTest
package com.Ministerstvo.Controller;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.Ministerstvo.Model.Ministerstvo;
import com.Ministerstvo.Service.MinisterstvoService;
import com.fasterxml.jackson.databind.ObjectMapper;
#WebMvcTest
#ExtendWith(MockitoExtension.class)
class MinisterstvoControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private MinisterstvoService ministerstvoService;
Ministerstvo ministerstvo;
List<Ministerstvo> zoznamMinisterstiev;
#BeforeEach
void setUp() throws Exception {
ministerstvo = Ministerstvo.builder()
.ministerstvoId(6L)
.ministerstvoName("MinisterstvoKultiry")
.ministerstvoEmail("kultura#gmail.com")
.ministerstvoPocetZamestnancov(5)
.build();
}
#AfterEach
void tearDown()
{
ministerstvo = null;
}
// DELETE TEST
// HOW IS THIS WORKING, WHEN I CREATE DB RECORD WITH ID 15, then delete ID 4 from endPoint for ID 55, and TEST passes?
#Test
void deleteMinisterstvo() throws Exception
{
Ministerstvo ministerstvoNadstranenie = Ministerstvo.builder()
.ministerstvoId(15L)
.ministerstvoName("Ministerstvo of Nothing")
.ministerstvoEmail("nothing#gmail.com")
.ministerstvoPocetZamestnancov(789)
.build();
doNothing().when(ministerstvoService).odstranMinisterstvo(4L);
// same result as from doNothing() above //doNothing().when(ministerstvoService).odstranMinisterstvo(ministerstvo.getMinisterstvoId());
// same result as from mockMvc.perform() below
//mockMvc.perform(delete("/ministerstva/55")
mockMvc.perform(delete("/ministerstva/"+ ministerstvoNadstranenie.getMinisterstvoId().toString())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
}
If i forgot to provide more details, i will add them based on instructions. I am just curious, if test for delete method is working properly, would be great to know the way, why test passes with different data.
Thanks for reading,
have a nice day
Have SpringBoot Java app with different classes. I am not able to inject the dependencies and initialize/access the object of one class into another . Have seen the spring doc and used the annotations (#component,#Autowired etc. ), still there is an issue.
following are the classes.
Main Class ()
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#SpringBootApplication
public class CostmanagementApplication {
public static void main(String[] args) {
SpringApplication.run(CostmanagementApplication.class, args);
}
}
Controller class
package com.test;
import javax.swing.text.rtf.RTFEditorKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Component
#Controller
public class HighChartsController {
#Autowired
private RequestToken rt;
#GetMapping("/costdata")
public static String customerForm(Model model) {
//here not able to access the getToken() method
model.addAttribute("costdata", new CostDataModel());
return "costdata";
}
}
RequestToken Class
package com.test;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.stream.Collectors;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
#Component
public class RequestToken {
public String getToken() throws IOException, InterruptedException {
// TODO Auto-generated method stub
// code to get the token
return token;
}
}
now eventhough , I have all annotation in place , not getting why the getToken() method is not accessible in controller class using rt object. please suggest
Okay, let's go in order.
First of all, all the annotations #Service, #Controller and #Repository are specifications from #Component, so you don't need to specify #Component and #Controller in your HighChartsController.
Actually, if you check what the annotation #Controller definition is, you'll find this:
#Component
public #interface Controller {
...
}
Secondly, I don't really know what do you mean with that you aren't able to access the getToken() method, but as you wrote it seems you tried to access to that method as an static method.
You're injecting the object, so you use the methods of the objects like in plain Java: rt.getToken(). The only difference is that the RequestToken object will be already initialized at the moment you call it.
package com.test;
import javax.swing.text.rtf.RTFEditorKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HighChartsController {
#Autowired
private RequestToken rt;
#GetMapping("/costdata")
public static String customerForm(Model model) {
String token = rt.getToken();
...
model.addAttribute("costdata", new CostDataModel());
return "costdata";
}
}
I need to mapping two GET methods look like:
GET /tickets - Retrieves a list of tickets
GET /tickets/12 - Retrieves a specific ticket
But when I mapped this, the Spring got confused!
When I hit http://localhost:8080/tickets in the Chrome, the result on server is:
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "tickets"]
When I hit http://localhost:8080/tickets/12 in the Chrome, the result on server is:
QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
My Spring controller is:
package wendelsilverio.api.ticket;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
#RestController("tickets")
public class TicketController {
#Autowired
private TicketRepository repository;
#GetMapping
public List<TicketEntity> getTickets() {
return repository.findAll();
}
#GetMapping("/{id}")
public Optional<TicketEntity> getTicket(#PathVariable("id") Long id) {
return repository.findById(Long.valueOf(id));
}
}
My unit test is:
package wendelsilverio.api.ticket;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#SpringBootTest
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class TicketControllerRestfulTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private TicketController mockTicketController;
#Test
public void getTickets() throws Exception {
given(mockTicketController.getTickets())
.willReturn(Arrays.asList(new TicketEntity(1L, "First ticket"), new TicketEntity(2L, "Second ticket")));
mockMvc.perform(get("tickets").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$[0].content", is("First ticket")))
.andExpect(jsonPath("$[1].content", is("Second ticket")));
}
#Test
public void getTicket12() throws Exception {
Optional<TicketEntity> twelveTicket = Optional.of(new TicketEntity(12L, "Twelve ticket"));
given(mockTicketController.getTicket(12L)).willReturn(twelveTicket);
mockMvc.perform(get("tickets/12").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(12L))).andExpect(jsonPath("$.content", is("Twelve ticket")));
}
}
I'm using Java 11 and Spring Boot 2.1.6
Use
#RestController
#RequestMapping("/tickets")
...
#GetMapping
...
#GetMapping("{id}")
In your code
1) #RestController("tickets") means 'create bean named "tickets"'
2) second URL (#GetMapping("/{id}")) tells 'put ID at root' (http://localhost:8080/ID) - so controller cannot convert 'tickets' to long.
I have an application example with a service:
RestApp.java
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/webapi")
public class RestApp extends Application {
#Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>();
classes.add(MessageService.class);
return classes;
}
}
MessageService.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.List;
#Stateless
#Path("/messages")
public class MessageService {
#Inject
private MessagesManager messagesManager;
#GET
#Path("all")
#Produces({MediaType.APPLICATION_JSON})
public List<Message> getMessages() {
return messagesManager.getMessages();
}
}
and the service depends on the singleton MessagesManager.java:
import javax.ejb.*;
import javax.inject.Singleton;
#Singleton
#Startup
#ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class MessagesManager implements Serializable {
private List<Message> messages = new ArrayList<>();
#Lock(LockType.READ)
public List<Message> getMessages() {
messages.add(new Message(1, "message text"));
return messages;
}
}
and this app works fine. But during the test occurs error of injection:
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=MessagesManager,parent=MessageService,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1232089028)
Test code is:
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals;
public class RestAppTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(MessageService.class);
}
#Test
public void testGet() {
final Response response = target("messages/all").request().get();
assertEquals(200, response.getStatus());
}
}
Why it happens and how to fix it?
The class MessagesManager is missing in an application context. Add the class to configure method like this:
return new ResourceConfig(MessageService.class, MessagesManager.class);
You need couple of things
1> Well formed JSON structure for your REST API
2> Some kind of REST client such as advanced REST client for chrome, Mozilla etc which can be used as a plugin. POSTMAN is also a useful tool
I am trying to create a test for a login page using JUnit where I need to mock out dev controller.
As I used a HttpServlet in my dev environment, for testing environment it is asking for httprequest...
I went for Mock request where my file is not getting where I'm using a controller not a servlet.
Can anyone help me on this?
Below is my JUnit Controller
package com.atoc.test.controller;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
import com.atoc.test.DAO.UserTestDAO;
import com.atoc.test.service.UserTestService;
import com.bpa.qaproduct.controller.UserController;
import com.bpa.qaproduct.entity.User;
import com.bpa.qaproduct.service.UserService;
import org.apache.commons.io.FileUtils;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "classpath:testApplicationContext.xml" })
public class UserControllerTest{
#Mock
private UserService userService;
#Mock
private HttpServletRequest request;
#Mock
private HttpServletResponse response;
#InjectMocks
private UserController userController;
private MockMvc mockMvc;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
#Test
public void testviewUserrList() throws Exception {
User user = new User();
//int value = null;
when(userService.getUserFilterCount(user)).thenReturn(20);
//mockMvc.perform(get("/todo/"));
mockMvc.perform(get("/user/viewUserList")).andExpect(status().isOk());
}
#Test
public void testloginVerification() throws Exception
{
User user = new User();
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
when(request.getParameter("userName")).thenReturn("me");
when(request.getParameter("password")).thenReturn("secret");
mockMvc.perform(post("/user/loginVerification"))
.andExpect(status().isOk());
System.out.println("***********"+request.getParameter("userName"));
}
}
The test case does not pass and httprequest is not passing values.
So I'm getting a NullPointerException in my running environment
I mocked out the request and response methods but I'm still getting the same error.
Passing value is not null
I'm giving some values there
setting time might be the problem
I didn't extend any Mockito in main class where I'm using inner methods
You have to provide request parameters to mockmvc instead of a request object.
#Test
public void testloginVerification() throws Exception {
User user = new User();
mockMvc.perform(post("/user/loginVerification")
.param("userName", "me")
.param("password", "secret"))
.andExpect(status().isOk());
}
Also the User object is not interacting with the other code of your test. I think you're doing something completely wrong. Can you add the code of the UserController?