Cannot resolve .andExpect() method even after implementing Stackoverflow answer - java

I am aware a question with the exact same title exists but the answer doesn't help me any further.
I am using WebMvcTest to test my controller class. However when it comes to comparing the result using .andExpect, my IDEA (intellij) can't resolve it.
The question with the same title as this one's solution is included in my imports and is unused. I also looked at the spring docs and used the 2 implements needed.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
Below you will find my entire class and in this case all my imports.
package be.pxl.backend.restapi;
import be.pxl.backend.restapi.controller.UserController;
import be.pxl.backend.restapi.domain.User;
import be.pxl.backend.restapi.manager.UserManager;
import org.junit.Test;
import org.junit.runner.RunWith;
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.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
//stackoverflow try == unused
import org.springframework.test.web.servlet.ResultActions;
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerIntegrationTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserManager userManager;
#Test
public void givenUser_WhenGetUser_ThenReturnUser() throws Exception{
User bjorn = new User();
bjorn.setUsername("Bjorn");
bjorn.setPassword("Wachtwoord");
bjorn.setEmail("test#email.be");
given(userManager.getUserById(1L)).willReturn(bjorn);
mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON)
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].username", is(bjorn.getUsername()))));
}
}

First of all, according to the Checkstyle, you should avoid star imports.
Secondly, you have misplaced two closing parentheses, one in contentType() and the other one in the last call of andExpect(). Below is a working code.
imports:
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.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 be.pxl.backend.restapi.controller.UserController;
import be.pxl.backend.restapi.domain.User;
import be.pxl.backend.restapi.manager.UserManager;
import org.junit.Test;
import org.junit.runner.RunWith;
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.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
Note the imports are ordered as per Google Java Style.
mock test:
mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].username", is(bjorn.getUsername())));

Related

Spring Boot REST API app, testing Controller layer with JUNIT

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

Android Powermockito how to mock toast

I am using powermockitor for test my login view model, and getting below issue when I answer for a mockitor case.
LoginViewModelTest.java
import android.app.Application;
import android.content.Context;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
#RunWith(PowerMockRunner.class)
#PrepareForTest(LoginViewModel.class)
#PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
public class LoginViewModelTest {
#Mock
private Context contextMock;
#Mock
private Application application;
#Rule
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testLogin_Succeed() throws Exception {
Mockito.doReturn(contextMock).when(application).getApplicationContext();
LoginViewModel loginViewModel = new LoginViewModel(application);
AuthApiService doctorApiServiceMock = Mockito.mock(AuthApiService.class);
Call<SessionResponse> responseCallMock = PowerMockito.mock(Call.class);
// Set mocks up to be returned when constructed. This can be moved to a #Before and should still work
PowerMockito.whenNew(AuthApiService.class)
.withAnyArguments()
.thenReturn(doctorApiServiceMock);
Mockito.doReturn(responseCallMock).when(doctorApiServiceMock).accessAppSession(anyString(), anyString());
Mockito.doAnswer((Answer<Callback<SessionResponse>>) invocation -> {
Callback<SessionResponse> callback = invocation.getArgument(0, Callback.class);
callback.onResponse(responseCallMock, Response.success(new SessionResponse()));
return null;
}).when(responseCallMock).enqueue(any(Callback.class));
loginViewModel.login("testUser","testPass");
}
}
Issuing case
java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.os.Looper.getMainLooper(Looper.java)
at android.arch.core.executor.DefaultTaskExecutor.postToMainThread(DefaultTaskExecutor.java:48)
at android.arch.core.executor.ArchTaskExecutor.postToMainThread(ArchTaskExecutor.java:101)
at android.arch.lifecycle.LiveData.postValue(LiveData.java:266)
at android.arch.lifecycle.MutableLiveData.postValue(MutableLiveData.java:28)
at com.cloudbreak.telemed.ui.login.LoginViewModel$1.onResponse(LoginViewModel.java:46)
at com.cloudbreak.telemed.LoginViewModelTest.lambda$testLogin_Succeed$1(LoginViewModelTest.java:91)
at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:39)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:96)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:35)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:61)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:49)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptAbstract(MockMethodInterceptor.java:126)
at retrofit2.Call$MockitoMock$1730005656.enqueue(Unknown Source)
at com.cloudbreak.telemed.ui.login.LoginViewModel.login(LoginViewModel.java:39)
at com.cloudbreak.telemed.LoginViewModelTest.testLogin_Succeed(LoginViewModelTest.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
I wanted to replace my JUnitRunner by Powermockrunnner (in order to further use features of Powermock that simple Mockito does not have). My LoginViewModel has posting value for a livedata state. How can I bypass this issuing case using mockito?

Junit throwing initialization error. Method 'com' not found

All the tests are passing . What should I add for this error to disappear? I am assuming some annotation need to be added. It says Method 'com' not found. I am not able to debug . I dont know what is it talking about.
Code:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class test {
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
private JdbcImpl jdbcImpl;
#Autowired
private MConfiguration config;
#Autowired
private MUtilities util;
#Test
public void testRetervices() throws Exception {
List<Tervice> marketServices = jdbcImpl.retrieveTervices("em", "Coitis");
assertEquals(marketServices.size(), 4);
}
Thanks for your time.
This got fixed when I changed the package from
import org.junit.jupiter.api.Test; to
import org.junit.Test;
Thanks!

The method andExpect(ResultMatcher) in the type ResultActions is not applicable for the arguments (RequestMatcher)

I am working on the Spring MVC + Mockito and I have developed the below code which is causing the error not sure what is wrong.
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
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 com.memorynotfound.config.WebConfig;
import com.memorynotfound.controller.UserController;
import com.memorynotfound.filter.CORSFilter;
import com.memorynotfound.model.User;
import com.memorynotfound.service.UserService;
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {WebConfig.class})
public class UserControllerUnitTest {
private MockMvc mockMvc;
#Mock
private UserService userService;
#InjectMocks
private UserController userController;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(userController).addFilters(new CORSFilter()).build();
}
#Test
public void test_get_all_success() throws Exception{
List<User> users = Arrays.asList(
new User(1, "Daenerys Targaryen"),
new User(2, "John Snow"));
when(userService.getAll()).thenReturn(users);
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].username", is("Daenerys Targaryen")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].username", is("John Snow")));
verify(userService, times(1)).getAll();
verifyNoMoreInteractions(userService);
}
}
I suspect, something related to the import statement not working.
#RestController
#RequestMapping("/users")
public class UserController {
private final Logger LOG = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
// =========================================== Get All Users ==========================================
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<User>> getAll() {
LOG.info("getting all users");
List<User> users = userService.getAll();
if (users == null || users.isEmpty()){
LOG.info("no users found");
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
}
Here is the error for reference:
java.lang.Error: Unresolved compilation problems:
The method andExpect(ResultMatcher) in the type ResultActions is not applicable for the arguments (RequestMatcher)
The method hasSize(int) is undefined for the type UserControllerUnitTest
The method is(int) is undefined for the type UserControllerUnitTest
The method is(String) is undefined for the type UserControllerUnitTest
The method is(int) is undefined for the type UserControllerUnitTest
The method is(String) is undefined for the type UserControllerUnitTest
The method times(int) is undefined for the type UserControllerUnitTest
at com.memorynotfound.test.UserControllerUnitTest.test_get_all_success(UserControllerUnitTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
I should have used this:
import static org.mockito.Mockito.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.*;
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 com.memorynotfound.config.WebConfig;
import com.memorynotfound.controller.UserController;
import com.memorynotfound.filter.CORSFilter;
import com.memorynotfound.model.User;
import com.memorynotfound.service.UserService;
I had the same problem. I discovered that there are two content classes; one for request and the other for result.
org.springframework.test.web.client.match.MockRestRequestMatchers.content;
org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
eclipse automatically imported the first MockRestRequestMatchers.content. The right class is MockMvcResultMatchers.content.
If you add the following import and delete the one imported by Eclipse. It should work.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
There are two tipes of content classes (request, response). If you want to fix quickly and add all the methods you have to import:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

Unit tests in Spring MVC Rest - cast issue

I am developing simple Rest API app and trying to test it using this tutorial: http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/
I have implemented entire test_get_all_success unit test using my working Rest API (written in Spring MVC). Unfortunately test cannot run because of following issue.
Here is entire test file:
import java.util.Arrays;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
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 static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={MyConfigClass.class})
#WebAppConfiguration
public class ClientTest {
private MockMvc mockMvc;
#Mock
private ClientManagerImpl clientManager;
#InjectMocks
private ClientController clientController;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(clientController)
.build();
}
#Test
public void findAll_ClientsFound_ShouldReturnFoundClients() throws Exception {
Client a = ...;
Client b = ...;
when(clientManager.getClients()).thenReturn(Arrays.asList(a, b));
mockMvc.perform(get("/clients"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(2)));
verify(clientManager, times(1)).getClients();
verifyNoMoreInteractions(clientManager);
}
}
NetBeans shows error in this line:
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
incompatible types: RequestMatcher cannot be converted to ResultMatcher
Test cannot run because of this error. When I delete this line everything works fine and test is passed.
What am I doing wrong?
The following static import causes the conflict:
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
MockRestRequestMatchers class is used for client-side REST testing using MockRestServiceServer, but you are testing here MVC application controllers.

Categories