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

Spring uses wrong codification for customized validation messages
Spring MVC autowire issue
The requested resource (/springHibernate) is not available
Automatic, contained testing of a web app
Grails Spring LDAP Security multiple domain use case
Make HSQL database persistent in LightAdmin (Spring/JPA/Hibernate)
SprigngTestDBUnit. How to ignore row order when comparing expected and actual datasets
What are the other use of Spring AOP except Logging and Exception handling?
Spring MVC 4.0 RESTFul Web Services
HTTP Status 404 Spring rest The requested resource is not available
Applying #PostFilter annotation to a generic Spring Data Jpa repository method
Multiple controllers per request
Deploy Spring + Hibernate + Maven + Google Cloud SQL application in Google App Engine
Is it possible to have an async message receiver in Spring AMQP that handles multiple content types?
Iterate over spring' session scoped beans
Hibernate Envers: AuditQuery throws ClasscastException

Categories

HOME
sharepoint
sidekiq
semantic-ui
google-contacts
d
deep-linking
ubuntu-12.04
travis-ci
quill
user
currency
ipfs
ndis
uiscrollview
nuxt.js
symfony-forms
future
jacoco
typeahead
bar-chart
apache-karaf
prestodb
styles
ip-camera
nmake
rails-activerecord
apple-tv
fop
facebook4j
tflearn
hanami
rhmap
lync-2013
emv
interrupt-handling
unpack
fetch-api
weinre
read-write
modulo
geomesa
google-guava-cache
liquid-xml
codesys
code-behind
parent
bing-translator-api
html-agility-pack
median
rkt
amd
lirc
livefyre
web-deployment-project
google-maps-ios
c64
spring-ioc
galleriffic
django-filer
pagekit
listadapter
mongoskin
asp.net-mvc-2
galaxy
servlet-3.0
insertion-sort
drf-nested-routers
hornetq
ninject.web.mvc
app.xaml
site-prism
kendo-menu
apigee-baas
paypal-nvp
base32
connection-reset
pylearn
git-checkout
ember-cli-addons
hiera
java-melody
gyroscope-framework
iostream
adaptive-compression
io.js
lumx
visualstatemanager
flash-cc
edit-in-place
layered
va-list
ruboto
localtime
justgage
lame
shortcuts
fileconveyor
process-monitor
arbor.js
vim-powerline
cadisplaylink
plone-funnelweb
makefile-project
nintendo
ubuntu-11.04
scraperwiki
datacontract
coff
noir
server-error
gwt-2.2-celltable
multibyte-functions
asp.net-mvc-controller
weborb
dotproject

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