Testing the controller which returns response entity - spring-boot

I have following the controller which accepts post request and returns Response Entity with body
#RestController
public class UserController {
#Autowired
private UserService UserService;
#RequestMapping(value = "/all", method = POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ResponseUser>> navigationTree(#RequestBody(required=false) UserDataRequest request) {
return UserService.sendEntries(request);
}
}
This is the test I wrote I for it:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class UserControllerTest {
private MockMvc mockMvc;
#MockBean
private UserService UserServiceMock;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setUp() {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
#Test
public void returnTopLevel() throws Exception {
String expectedJson = "[{\"id\":\"11\",\"name\":\"11\"},{\"id\":\"22\",\"name\":\"22\"}]";
MvcResult result = this.mockMvc.perform(post("/all")
.contentType(MediaType.APPLICATION_JSON)
.content("")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
String actualJson = result.getResponse().getContentAsString();
// System.out.println(result);
//assertThat(Objects.equals(expectedJson, actualJson)).isTrue();
verify(UserServiceMock,times(1)).sendEntries(null);
}
}
I want to compare string received in response body to expected string.
I tried the string comparison but it's not working
Errors :
assertThat(Objects.equals(expectedJson, actualJson)).isTrue();
and actualjson is empty.
What are the other ways?

You need to mock the UserService to return something before executing this.mockMvc.perform. Something like this:
when(UserServiceMock.sendEntries(null)).thenReturn(expectedResponceEntity);
So just construct the expected response then mock UserService to return it.

Related

Why Testing Controller not working with #RunWith(SpringRunner.class) & #WebMvcTest annotation?

I am getting the below error when I try to run my controller test. Please can you let me know what I am missing? Why should I add the #ContextConfiguration or #SpringBootTest ?
java.lang.IllegalStateException: Unable to find a #SpringBootConfiguration, you need to use #ContextConfiguration or #SpringBootTest(classes=...) with your test
#Controller
public class BasketController {
#Autowired
private BasketService basketService;
#GetMapping(value="/baskets/{basketId}")
public ResponseEntity<BasketDto> getBasket(#PathVariable("basketId") UUID basketId){
Basket basket = basketService.getBasket(basketId);
BasketDto dto = toBasketDto(basket);
ResponseEntity response = ResponseEntity.status(HttpStatus.OK).body(dto);
return response;
}
private BasketDto toBasketDto(Basket basket){
BasketDto dto = new BasketDto(basket.getBasketId(), basket.getItems());
return dto;
}
}
#RunWith(SpringRunner.class)
#WebMvcTest(BasketController.class)
public class BasketControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private BasketService basketService;
#Test
public void testGetItemsInBasketSuccessfully() throws Exception {
UUID basketId = UUID.randomUUID();
String URI = "/api/baskets/" + basketId;
Basket mockBasket = new Basket(basketId);
Mockito.when(basketService.getBasket(basketId)).thenReturn(mockBasket);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI).accept(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String actualJson = result.getResponse().getContentAsString();
System.out.println(actualJson);
}
}

MockMvc response returns 404, expected response 201

I am new to unit testing REST API in Spring Boot.
I am expecting response status as CREATED but instead I am getting a PAGE NOT FOUND error.
Below is the code for:-
UserControllerUnitTests
#SpringBootTest
#ContextConfiguration(classes = { CommonConfig.class, SecurityConfig.class})
#RunWith(SpringRunner.class)
class UserControllerUnitTests {
private static ObjectMapper mapper;
private static final String URI = "/users";
MockMvc mvc;
#Autowired
WebApplicationContext webAppContext;
#Mock
UserService userService;
MvcResult mvcResult;
#BeforeAll
static void setUp() {
mapper = new ObjectMapper();
}
#BeforeEach
void initialize() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
....
....
....
void shouldReturnStatusCreatedIfValidUserPassedForPostUser(long index) throws Exception {
int expectedStatus = HttpStatus.CREATED.value();
UserDAO returnUser;
UserDAO user = userList.get(index);
userList.remove(index);
String jsonContent = mapper.writeValueAsString(user);
user.setId(index);
user.setEncryptedPassword(null);
Mockito.when(userService.addUser(Mockito.any())).thenReturn(user);
mvcResult = mvc.perform(MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonContent)).andReturn();
//Mockito.verify(userService, Mockito.times(1)).addUser(Mockito.any());
int actualStatus = mvcResult.getResponse().getStatus();
Assert.assertEquals("Response status should be CREATED", expectedStatus, actualStatus);
jsonContent = mvcResult.getResponse().getContentAsString();
returnUser = mapper.readValue(jsonContent, UserDAO.class);
Assert.assertEquals("EncryptedPassword should not be returned", null,
returnUser.getEncryptedPassword());
}
User Controller.class
#RestController
#RequestMapping("users/")
public class UserController {
UserService userService;
#Autowired
public UserController(UserService userService) {
this.userService = userService;
}
....
....
....
#PostMapping(path = "",
consumes = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON },
produces = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ResponseEntity<UserDAO> createUser(#Valid #RequestBody UserDAO user) {
String password = user.getEncryptedPassword();
user.setEncryptedPassword(null);
UserDAO retreivedUser;
if(user.getId() != 0)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
user.setEncryptedPassword(password);
retreivedUser = userService.addUser(user);
if(retreivedUser != null)
return new ResponseEntity<>(retreivedUser, HttpStatus.CREATED);
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
}
The full code can be found at https://github.com/vineethmaller/springboot-userservice
I spotted a few errors:
Get rid of ContextConfiguration
#SpringBootTest
// #ContextConfiguration(classes = { CommonConfig.class, SecurityConfig.class})
#RunWith(SpringRunner.class)
class UserControllerUnitTests {
Specify correct mapping on the controller (no slash)
#RestController
#RequestMapping("users")
public class UserController {
You setup your UserService mock which is not used in the test. Did you mean #MockBean?
#MockBean
UserService userService;

Want to Mock ValidationofToken in restcontroller junit testing

Need to skip a Validation of token id login in controller for unit testing
Not sure what to use Mock or spy since i'm testing the controller itself
public class TestController extends BaseController {
#Autowired
TestService service;
#RequestMapping(value = "/test")
public #ResponseBody TestResponse getAll(#RequestBody TestRequest request) {
validateToken(request);
TestResponse response = service.getall(request);
response.setTokenID(request.getTokenID());
return response;
}
}
public class BaseController {
protected void validateToken(IRequest request) {
TokenResponse tokenresponse = restTemplate.exchange(TokenServiceURL, HttpMethod.GET, null, TokenResponse .class, tokenId).getBody();
User user = new user()
user.setUserRole(tokenresponse.getUser()));
request.setUser(user);
}
}
public class TestControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext wac;
#Autowired
private TestController testControlller;
#MockBean
private TestService testService;
BaseController baseControllerSpy = Mockito.spy(BaseController.class);
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
#Test
public void verifygetAll() throws Exception {
TestRequest request = new TestRequest();
TestResponse response = new Response();
**Mockito.doNothing().when(baseControllerSpy).validateTokenID(request);**
when(testService.get(request)).thenReturn(response);
mockMvc.perform(MockMvcRequestBuilders.post("/test")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
}
}
Base controller being spy doesn't seem to work, is there any other way i can approach this scenrio. please help
I can advice you two solutions:
I assume that if you are in the same package then you have to inject a spy of TestController in the mockMvc when you do the build() then you can create the validateToken mockMvc
doNothing().when((BaseController)testController).validateTokenID(any());
If the previous solution is not compliant then you can extend the TestController class with the TestControllerForTest and you can make the override of the validateTokenID method where you do nothing.

Testing REST API with MOCKITO

I have a problem with testing the REST API using MOCKITO
I have an example of the rest controller code:
#RestController
#RequestMapping(path = "api/workers")
public class WorkOfferController {
#Autowired
private WorkerService workerService;
#PostMapping(value = "/lists", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity searchWorker(#RequestBody RecruitmentSearchRequest recruitmentSearchRequest, #RequestParam("page") int page, #RequestParam("size") int size,) throws NoSuchFieldException {
System.err.print('WorkerController');
return workerService.getWorkers(recruitmentSearchRequest, page, size);
}
}
And the right service for it:
#Service
#Transactional
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class WorkerService {
private final WorkerRepistory workerRepository;
private final UserRepository userRepository;
public ResponseEntity getWorkers(RecruitmentSearchRequest recruitmentSearchRequest,int pageNumber, int size) throws NoSuchFieldException {
System.err.print('WorkerService');
...
}
}
I want to test whether everything is okay under the url with the right data. I do not want to use this database because I prefer Mockito.
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#SpringBootTest(classes = Appp2workApplication.class)
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PharmacyWorkOfferRestDocsTests {
private MockMvc mockMvc;
#InjectMocks
private WorkOfferController workOfferController;
#Mock
private WorkerService workerService;
#Mock
UserRepository userRepository;
#Mock
WorkerRepistory workerRepository;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(workOfferController).build();
}
#Test
public void searchWorkOfferListWithParameters() throws Exception {
String payload = "{\n" +
"\t\"name\":\"tomek\",\n" +
"\t\"searchFromSalary\":5,\n" +
"}";
Mockito.doNothing().when(userRepository.save(Mockito.anyObject()));
Mockito.when(searchService.getRecruitmentOfferJobListWithParameters(Mockito.anyObject())).thenReturn(list);
this.mockMvc.perform(post("/api/workers/lists?page=0&size=20").contentType(MediaType.APPLICATION_JSON).content(payload))
.andExpect(status().isOk());
}
}
And I have a problem that with this approach the test comes to me in the controller and displays "WorkerController" but I do not want to enter the service from this controller, and it returns 200, but it really only came to the controller and that's it. This is probably because WorkerService is as Mock but I tried to give it as eg Autowired or InjectMock and it is still the same.
What do I do wrong that I enter into the controller but I do not want to use this controller for the appropriate service?

Null Pointer Exception while calling a RestController using Mockmvc perform() method in SpringBoot

I am using MockMvc for the first type. What I am doing is testing a Restcontroller in SPringboot.
I have a Restcontroller like this,
#RequestMapping("/address")
public class AddressController {
#RequestMapping("/createAddress")
public Address craeteAddress(Address address)
{
Address add=addressService.createAdd(address);
return add;
}
#RequestMapping("/getAll")
public List<Address> getAll()
{
return addressService.getAll();
}
}
Now my test class looks like this,
public class AddressControllerTest {
AddressService addressService = mock(AddressService.class);
#Autowired
MockMvc mockMvc;
private static final String ADDRESS_DTO_JSON =
"{" +
"\"id\":\"123\"," +
"\"pacsId\":\"345\"," +
"}";
List<Object> object = new ArrayList<Object>();
#Before
public void setup() {
}
#Test
public void createAddressTest() throws Exception {
//System.out.println("The Json Content :" + ADDRESS_DTO_JSON);
this.mockMvc
.perform(get("address/getAll"))
.andExpect(status().isOk())
.andReturn();
}
}
I am trying to call the 'address/getAll' method in the restcontroller. When i run the junit method it says 'Null Pointer Exception' near the .perform(get("address/getAll")) line.
I did some research but did not work out. Can someone please help ?
I think you misconfigured your test class.
Try something like this:
#RunWith(SpringRunner.class)
#WebMvcTest(AddressController.class)
public class AddressControllerTest {
#Autowired
MockMvc mockMvc;
}

Resources