spring


How to unit testing spring boot rest controller and exception handler using power mock


I am having a simple Spring boot application which contains Employee controller which returns the Employee names if the year passed is greater than 2014 and if the it is not less than 2014 then I am throwing a custom exception and handling it in Exception Handler. I want to unit test the exception flow using powermock but I am not sure how to do it. I have gone through some links but unable to understand.
Currently I am getting java.lang.IllegalArgumentException: WebApplicationContext is required.
EmployeeController.java
#RestController
public class EmployeeController{
#GetMapping(value = "/employee/{joiningYear}",produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> getEmployeeById(#PathVariable int joiningYear) throws YearViolationException {
if(joiningYear < 2014){
throw new YearViolationException("year should not be less than 2014");
}else{
// send all employee's names joined in that year
}
return null;
}
}
ExceptionHandler
#RestControllerAdvice
public class GlobalControllerExceptionHandler {
#ExceptionHandler(value = { YearViolationException.class })
#ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiErrorResponse yearConstraintViolationExceptio(YearViolationException ex) {
return new ApiErrorResponse(400, 5001, ex.getMessage());
}
}
CustomException
public class YearViolationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public YearViolationException(String message) {
super(message);
}
}
Junit to unit test exception handler
#RunWith(PowerMockRunner.class)
#WebAppConfiguration
#SpringBootTest
public class ExceptionControllerTest {
#Autowired
private WebApplicationContext applicationContext;
private MockMvc mockMVC;
#Before
public void setUp() {
mockMVC = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}
#Test
public void testhandleBanNotNumericException() throws Exception {
mockMVC.perform(get("/employee/2010").accept(MediaType.APPLICATION_JSON)).andDo(print())
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
}
As stated by others, you don't need mockMVC at all. If you want to test REST endpoints, what you need is TestRestTemplate.
Runwith SpringRunner.class is important as well as the WebEnvironment setup.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class RestServiceApplicationTests {
private String baseUrl = "http://localhost:8090";
private String endpointToThrowException = "/employee/2010";
#Autowired
private TestRestTemplate testRestTemplate;
#Test(expected = YearViolationException.class)
public void testhandleBanNotNumericException() {
testRestTemplate.getForObject(baseUrl + endpointToThrowException, String.class);
}
From how your setup looks, you don't need to use Mocks at all. It seem's like you want to load the complete application context and use mockMVC to send requests against your rest controller. This is actually and integrationtest!
Now, unfortunately we use Spring Boot 1.3 here, so I'm not sure if the combination of #RunWith(PowerMockRunner.class) and #SpringBootTest in fact loads the Application context. Check your logs and see if it does and if not, try this:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
If, on the other hand you want to make a simple unit test, then you don't need to load the application context. Instead you can just use regular Mockito with #Mock and #InjectMocks in conjuntion with #RunWith(MockitoJUnitRunner.class) and call the method you want to test directly as you would any other method under test.
Hope this help.

Related Links

No session found for current thread. Works in local QA, fails in production
Error creating bean with name 'messageSource' defined in ServletContext
Plugin execution not covered by lifecycle configuration
Spring Security authenticationFailure
How to use a singleton Session factory in an application with multiple modules
Spring Data Rest integration with Spring HATEOAS
Bi-directional messaging with spring integration
Spring MVC #Controller creates empty response
Get all users belonging to a Role/Roles
how to get my Current custom User in Spring Security?
How can I get user's logged Id from SecurityContextHolder using Spring Social?
Spring webflow json response validation before Transition
Spring how to get Maven artifact name in runtime
Failed to load ApplicationContext in unitTests no-xml spring
integrating jsf2.1 Spring 4
Spring Hibernate ConverterNotFoundException ManyToMany

Categories

HOME
ibm-watson-cognitive
vb6
translation
jasmine
cpu-architecture
json-ld
amazon-product-api
command
transparent
phpstorm
apollo
adsense
urlencode
cartodb
lagom
spinnaker
abcpdf
scala-native
python-unicode
zoomcharts
off-canvas-menu
backpropagation
uiautomator
apple-tv
tflearn
scalajs-react
switching
opencart2.3
rhandsontable
classpath
edge-detection
ggmap
vertex-buffer
jackson-dataformat-csv
spreedly
office365connectors
xamarin.uitest
tic-tac-toe
infusionsoft
polyfills
rule
lexical-analysis
g1gc
intersystems-ensemble
catia
php-ews
tableau-server
nsjsonserialization
rollback
maintenance
chrome-remote-desktop
windows-95
ticker
react-native-fbsdk
selenium-firefoxdriver
sqlexception
onresume
ebtables
manifest.mf
vst
gitweb
django-south
concur
asp.net-mvc-2
spservices
license-key
retro-computing
textkit
paypal-nvp
visual-studio-code
integral
graphical-logo
ubercart
debian-based
gray-code
lines-of-code
google-hadoop
jython-2.7
magento-1.12
inputaccessoryview
cpu-speed
gyroscope-framework
node-inspector
argument-passing
voldemort
visualstatemanager
dynamic-proxy
logentries
dllexport
htmltextwriter
code-conversion
couchdb-lucene
redirectstandardoutput
subtract
signals2
visual-web-gui
point-sprites
hobo
selectonemenu
selectmanycheckbox
dashcode
email-spec
asp.net-routing
recordset
aio
trampolines
grooveshark
pci-bus
ajaxpro

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App