How to write unit testing checking null input values using wicket - wicket

I am busy with a wicket application and need to do unit testing, and I have a login page that validates inputs from a List<Customer> but I have no idea where to start, I did try something but it gave me errors and just have no clue what I am doing any help is appreciated
Homepage.java
form.add(new AjaxButton("error") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target)
{
for (Customer item: lstCustomer){
if (item.name.equals(username.getInput()) && item.password.equals(password.getInput())){
final String usernameValue = username.getModelObject();
PageParameters pp = new PageParameters();
pp.add("username", usernameValue);
setResponsePage(SuccessPage.class, pp);
valid[0] = true;
break;
}else {
logger.error("In the else");
valid[0] = false ;
}
}
if ( valid[0] == false){
errorDialog.open(target);
}
}
});
TestPage
private WicketTester tester;
#Before
public void setUp()
{
tester = new WicketTester(new WicketApplication());
}
#Test
public void homepageRendersSuccessfully()
{
//start and render the test page
tester.startPage(HomePage.class);
//assert rendered page class
tester.assertRenderedPage(HomePage.class);
}
#Test
public void validLogin(){
FormTester form = tester.newFormTester("userForm");
form.setValue("username", "emile");
form.setValue("password", "123");
form.submit();
tester.assertRenderedPage(SuccessPage.class);
}
And then I get this error :
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket jQuery UI initializer (theme-uilightness)
java.lang.NullPointerException
at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1593)
at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1516)
at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1625)
at org.apache.wicket.util.tester.BaseWicketTester.newFormTester(BaseWicketTester.java:1311)
at org.apache.wicket.util.tester.BaseWicketTester.newFormTester(BaseWicketTester.java:1295)
at com.mycompany.TestHomePage.validLogin(TestHomePage.java:35)
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.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)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

you must set a starting page in validLogin() before creating a formTester:
#Test
public void validLogin(){
//here...
tester.startPage(HomePage.class);
FormTester form = tester.newFormTester("userForm");
form.setValue("username", "emile");
form.setValue("password", "123");
form.submit();
tester.assertRenderedPage(SuccessPage.class);
}

In your validLogin() method you need to start with tester.startPage(SomePage.class).
startPage() is the same as navigating to a address in the browser. You cannot login to some web app without navigating to its login page first.
You can also use #startComponentInPage(LoginPanel.class). Here Wicket will add your LoginPanel into a dummy page for you. And you can assert that the LoginPanel behaves the way you need.
This way you could test any kind of Wicket Component, not just Panel.

Related

Class not found when trying to return List from consumeEvent in Quarkus

When I try to return a Uni with a typed java.util.List in Quarkus in dev mode, i get a ClassNotFound exception. I have read about Quarkus using different class loaders in different profiles, but I don't see that I do anything fancy.
Here's the sender
#Query("offers")
public Uni<List<OfferResponse>> getOffers(#PathParam("category") Integer categoryId) {
OfferRequest event = new OfferRequest();
event.setCategoryId(categoryId);
Uni<List<OfferResponse>> offers = bus.<List<OfferResponse>>request(OfferRequest.ADDRESS, event).onItem().transform(Message::body);
return offers;
}
And here's the consumer
#ConsumeEvent(OfferRequest.ADDRESS)
public Uni<List<OfferResponse>> onOfferQuery(OfferRequest request) {
List<KelkooOffer> offers = getOffers(request.getCategoryId());
List<OfferResponse> responses = new ArrayList<OfferResponse>();
for (KelkooOffer offer : offers) {
responses.add(offer.getEventResponse());
}
return Uni.createFrom().item(responses);
}
The bean I'm trying to return is just a POJO
and the error message
2021-08-18 11:11:16,186 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile dev): java.lang.ClassNotFoundException: java.util.List<se.bryderi.events.OfferResponse>
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:405)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:405)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at io.quarkus.deployment.steps.VertxProcessor$build609260703.deploy_0(VertxProcessor$build609260703.zig:142)
at io.quarkus.deployment.steps.VertxProcessor$build609260703.deploy(VertxProcessor$build609260703.zig:40)
at io.quarkus.runner.ApplicationImpl.doStart(ApplicationImpl.zig:784)
at io.quarkus.runtime.Application.start(Application.java:101)
at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:101)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:66)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:42)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:119)
at io.quarkus.runner.GeneratedMain.main(GeneratedMain.zig:29)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:98)
at java.base/java.lang.Thread.run(Thread.java:829)
I get the same result if I run the dev profile or if I run the packaged fast-jar.
Happy for any hint that will point me in the right direction
There is a limitation of the Vert.x EventBus which prevents to encode/decode lists or sets directly.
You could create a wrapper for your OfferResponse list:
import java.util.AbstractList;
import java.util.List;
public class OfferResponseList extends AbstractList<OfferResponse> {
private List<OfferResponse> wrapped;
private OfferResponseList(List<OfferResponse> wrapped) {
this.wrapped = wrapped;
}
public static OfferResponseList wrap(List<OfferResponse> list) {
return new OfferResponseList(list);
}
#Override
public OfferResponse get(int index) {
return wrapped.get(index);
}
#Override
public int size() {
return wrapped.size();
}
}
Then transform your consumer to:
#ConsumeEvent(OfferRequest.ADDRESS)
public Uni<OfferResponseList> onOfferQuery(OfferRequest request) {
List<KelkooOffer> offers = getOffers(request.getCategoryId());
List<OfferResponse> responses = new ArrayList<OfferResponse>();
for (KelkooOffer offer : offers) {
responses.add(offer.getEventResponse());
}
// Notice the call to OfferResponseList.wrap here
return Uni.createFrom().item(OfferResponseList.wrap(responses));
}
That's it. Quarkus will register a codec for OfferResponseList automatically.
On the client side, you do not need to change your code:
#Query("offers")
public Uni<List<OfferResponse>> getOffers(#PathParam("category") Integer categoryId) {
OfferRequest event = new OfferRequest();
event.setCategoryId(categoryId);
// You can use Uni<List<OfferResponse>> or Uni<OfferResponseList>
Uni<List<OfferResponse>> offers = bus.<List<OfferResponse>>request(OfferRequest.ADDRESS, event).onItem().transform(Message::body);
return offers;
}

Task not serializable : Spark

My spark job is throwing Task not serializable at runtime. Can anyone tell me if what i am doing wrong here?
#Component("loader")
#Slf4j
public class LoaderSpark implements SparkJob {
private static final int MAX_VERSIONS = 1;
private final AppProperties props;
public LoaderSpark(
final AppProperties props
) {
this.props = props;
}
#Override
public void run(SparkSession spark, final String... args) throws IOException {
HBaseUtil hBaseUtil = new HBaseUtil(props);
byte[][] prefixes = new byte[][]{toBytes("document"),
toBytes("dataSource"),
toBytes("hold:")};
Filter filter = new MultipleColumnPrefixFilter(prefixes);
Scan scan = new Scan();
scan.addFamily(toBytes("data"));
scan.setCaching(100000);
scan.setMaxVersions(MAX_VERSIONS);
scan.setFilter(filter);
JavaRDD<TestMethod> mapFileJavaRDD
= hBaseUtil.createScanRdd(spark, "TestTable", scan).mapPartitions(tuple -> {
return StreamUtils.asStream(tuple)
.map(this::extractResult)
.filter(Objects::nonNull)
.iterator();
});
Dataset<TestMethod> testDataset = spark.createDataset(mapFileJavaRDD.rdd(), bean(TestMethod.class));
testDataset.limit(100);
}
private TestMethod extractResult(Tuple2<ImmutableBytesWritable, Result> resultTuple) {
TestMethod.TestMethodBuilder testBuilder = TestMethod.builder();
Result result;
result = resultTuple._2();
CdfParser cdfParser = new CdfParser();
List<String> holdingId = new ArrayList<>();
testBuilder.dataSource(Bytes.toString(result.getValue(Bytes.toBytes("data"),
Bytes.toBytes("dataSource"))));
testBuilder.document(cdfParser.fromXml(result.getValue(Bytes.toBytes("data"),
Bytes.toBytes("document"))));
NavigableMap<byte[], byte[]> familyMap = result.getFamilyMap(Bytes.toBytes("data"));
for (byte[] bQunitifer : familyMap.keySet()) {
if (Bytes.toString(bQunitifer).contains("hold:")) {
LOG.info(Bytes.toString(bQunitifer));
holdingId.add(Bytes.toString(bQunitifer));
}
}
testBuilder.holding(holdingId);
return testBuilder.build();
}
}
HERE is the stacktrace:
2020-04-29 12:48:59,837 INFO [Thread-4]o.a.s.d.y.ApplicationMaster: Unregistering ApplicationMaster with FAILED (diag message: User class threw exception: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:787)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:768)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322)
at org.oclc.googlelinks.spark.SpringSparkJob.main(SpringSparkJob.java:56)
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.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:694)
Caused by: org.apache.spark.SparkException: Task not serializable
at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:393)
at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:798)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:797)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:797)
at org.apache.spark.api.java.JavaRDDLike$class.mapPartitions(JavaRDDLike.scala:155)
at org.apache.spark.api.java.AbstractJavaRDDLike.mapPartitions(JavaRDDLike.scala:45)
at org.oclc.googlelinks.spark.job.LoaderSpark.run(LoaderSpark.java:79)
at org.oclc.googlelinks.spark.SpringSparkJob.run(SpringSparkJob.java:79)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784)
... 8 more
try adding getter and setters for props
public void setProps(AppProperties props) {
this.props = props;
}
public AppProperties getProps() {
return props;
}
Just make the function extractResult static . In order to call a static method, you don’t need to serialize the class, you need the declaring class to be reachable by the classloader (and it is the case, as the jar archives can be shared among driver and workers).
Thanks to https://www.nicolaferraro.me/2016/02/22/using-non-serializable-objects-in-apache-spark/

Unexpected error while Controller unit test

I am learning unit testing. I have implemented unit test for the spring boot controller in my sample project. When I run the test class, every time it returns 400 status (Expected 200). After i did a research and I have found that if(entity.getStatusCode().equals(HttpStatus.OK)) { is line which gives exception. It might be because it uses return of Service2.
However, code is working fine without running test cases. I have attached MyController and MyControllerTest classes.
My Controller
#RestController
#RequestMapping("/user")
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserManagementService userManageService;
#Autowired
private AdminManagementService adminManageService;
#Autowired
private AuthenticateManagementService authService;
#PutMapping("/change-password")
public ResponseEntity<?> changePassword(#RequestHeader("Authorization") String token,
#RequestBody PasswordChangeRequestDTO passwordChangeRequestDTO) {
ResponseDTO finalResponse = new ResponseDTO();
try {
LOGGER.info("Changing user password.");
KeycloakLoginResponseDTO keycloakResponse = authService.auhtenticate(passwordChangeRequestDTO.getLoginRequestDTO());
ResponseEntity<?> logoutEntity = authService.logout(token, keycloakResponse.getSession_state());
if(logoutEntity.getStatusCode().equals(HttpStatus.OK)) {
LOGGER.info("User password matched");
}
String userId = adminManageService.getUserByName(token, passwordChangeRequestDTO.getLoginRequestDTO().getUsername());
ResponseEntity<?> entity = userManageService.changePassword(token, passwordChangeRequestDTO, userId);
LOGGER.info("USER : " + "" +"has successfully changed password.");
finalResponse.setMessageCode(HttpStatus.OK);
finalResponse.setMessage("Password changed successfully");
finalResponse.setError(false);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.ok().body(finalResponse);
return finalEntity;
}catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error has occured while changing password of USER : " + "" + ".");
finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
finalResponse.setMessage("Oops! Looks like you have entered the wrong password in the 'Old Password' field");
finalResponse.setMessageDetail(e.getMessage());
finalResponse.setError(true);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.badRequest().body(finalResponse);
return finalEntity;
}
}
}
Controller Unit test class
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserManagementService userManageService;
#MockBean
private AdminManagementService adminManageService;
#MockBean
private AuthenticateManagementService authService;
#InjectMocks
private UserController userController;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testChangePasswordhappyPath() throws Exception {
PasswordChangeRequestDTO passwordChangeRequestDTO = new PasswordChangeRequestDTO();
LoginRequestDTO loginRequestDTO = new LoginRequestDTO();
loginRequestDTO.setClient_id("test_client");
loginRequestDTO.setGrant_type("test_grant_type");
loginRequestDTO.setPassword("test_password");
loginRequestDTO.setUsername("test_user");
CredentialsRequestDTO credentialsRequestDTO = new CredentialsRequestDTO();
credentialsRequestDTO.setTemporary(false);
credentialsRequestDTO.setType("password");
credentialsRequestDTO.setValue("test_password");
passwordChangeRequestDTO.setLoginRequestDTO(loginRequestDTO);
passwordChangeRequestDTO.setCredentialsRequestDTO(credentialsRequestDTO);
ResponseEntity<String> mockResponse = new ResponseEntity<String>("", HttpStatus.OK);
when(userManageService.changePassword("Token", passwordChangeRequestDTO, "UserId")).thenReturn(mockResponse);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(passwordChangeRequestDTO);
mockMvc.perform(put("/user/change-password", passwordChangeRequestDTO)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Token")
.content(json)
.characterEncoding("utf-8"))
.andExpect(status().isOk()).andReturn();
}
}
What am i doing wrong here. Is there anything to add to my MyControllerTest class or How can i cover this test case. Any help would be grateful.
UPDATED
I have also added e.printStackTrace()
java.lang.NullPointerException
at com.mycode.controller.UserController.changePassword(UserController.java:39)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.mycode.controller.UserControllerTest.testChangePasswordhappyPath(UserControllerTest.java:71)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Why does JerseyTest throw ConstraintViolationException instead of returning 400 Bad Request?

I am using Jersey version 2.23.2 and I am unable to figure out how to use JerseyTest to test the responses for when validation fails. For some reason, the below test throws a ConstraintViolationException which is wrapped in a ProcessingException instead of returning 400 Bad Request. I could modify the test to check that the ProcessingException is thrown, but I really want to test the response. When I run HelloResource in Grizzly without JerseyTest, I get the appropriate 400 Bad Request response. Any ideas on how to fix the badRequestResponse() test below?
package example;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import static org.junit.Assert.assertEquals;
public class BadRequestTest extends JerseyTest {
#XmlAccessorType(XmlAccessType.FIELD)
public static class Hello {
#NotNull(message = "Name is a required field.")
private final String name;
private Hello() {
this(null);
}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#Path("hello")
public static class HelloResource {
#POST
public String sayHelloToMe(#Valid Hello hello) {
return "Hello " + hello.getName() + "!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class).property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
}
/** Test OK Response. This Works!*/
#Test
public void okResponse() {
Response response = target("hello")
.request(MediaType.TEXT_PLAIN)
.post(Entity.json(new Hello("Tiny Tim")));
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Hello Tiny Tim!", response.readEntity(String.class));
}
/** Test Bad Request Response. This Fails! */
#Test
public void badRequestResponse() {
Response response = target("hello")
.request(MediaType.TEXT_PLAIN)
.post(Entity.json(new Hello(null)));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
Here's the exception I am getting:
javax.ws.rs.ProcessingException:
Exception Description: Constraints violated on marshalled bean:
example.BadRequestTest$Hello#456abb66
-->Violated constraint on property name: "Name is a required field.".
Internal Exception: javax.validation.ConstraintViolationException
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:261)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
at example.BadRequestTest.badRequestResponse(BadRequestTest.java:70)
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.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)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: Exception [EclipseLink-7510] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.BeanValidationException
Exception Description: Constraints violated on marshalled bean:
example.BadRequestTest$Hello#456abb66
-->Violated constraint on property name: "Name is a required field.".
Internal Exception: javax.validation.ConstraintViolationException
at org.eclipse.persistence.exceptions.BeanValidationException.constraintViolation(BeanValidationException.java:53)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:385)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.validate(JAXBBeanValidator.java:273)
at org.eclipse.persistence.jaxb.JAXBMarshaller.validateAndTransformIfNeeded(JAXBMarshaller.java:588)
at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:481)
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:517)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:499)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:388)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
... 39 more
Caused by: javax.validation.ConstraintViolationException
at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:383)
... 52 more
This is a client side problem. As you've discovered MOXy has bean validation on by default. So you are getting bean validation on the client. So the request is not even going through as the error is happening on the client. You could test this by just sending a string
Entity.json("{}")
That should get rid of the error. But if you want to use the bean, as you mentioned in the comment, you should disable the bean validation on the client with MOXy
#Override
protected void configureClient(final ClientConfig config) {
super.configureClient(config);
config.register(new MoxyJsonConfig()
.property(MarshallerProperties.BEAN_VALIDATION_MODE,
BeanValidationMode.NONE).resolver());
}

Unit testing Spring Boot MultiPartFile PDF Upload Rest Controller using MockMvc

Good day Pals,
I am new to Springboot and having problems testing my PDF uploader spring controller endpoint.
The rest endpoint works when tested via postman, but not in my unit test.
I am using a spring boot application with the following key components and problem is:
org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:251)
2016-06-09 19:03:03,359 4198 [main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext#646be2c3 testClass = PDFUploadControllerTest, testInstance = x.y.z.rest.controller.PDFUploadControllerTest#2b44d6d0, testMethod = testHandleFileUpload#PDFUploadControllerTest, testException = java.lang.AssertionError: Status expected:<200> but was:<400>, mergedContextConfiguration = [WebMergedContextConfiguration#797badd3 testClass = PDFUploadControllerTest, locations = '{}', classes = '{class x.y.z.rest.PresentationConfiguration, class x.y.z.rest.controller.MockDomainConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].
java.lang.AssertionError: Status
Expected :200
Actual :400
Please, see some code and stacktrace below ... I have been banging my head on the wall all day, debugging using all online references but NO luck ....
Your help will be most appreciated. Thanks
Application
#EnableAutoConfiguration()
public class Application {
public static void main(String[] args) {
SpringApplication.run(
new Object[]{
DomainConfiguration.class,
PresentationConfiguration.class
},
args);
}
}
DomainConfiguration
#Configuration
#EnableAutoConfiguration()
#ComponentScan(basePackages = {
"x.y.z.rest.domain",
"x.y.z.rest.service",
"x.y.z.rest.util",
"x.y.z.rest.repository"
})
public class DomainConfiguration {
#Autowired(required = true)
public void configeJackson(ObjectMapper jackson2ObjectMapper) {
jackson2ObjectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
PresentationConfiguration
#Configuration
#ComponentScan(basePackages = {"x.y.z.rest.controller"})
public class PresentationConfiguration {
}
## RestController
#RestController
public class PDFUploadController {
#Autowired
public void setUploadService(UploadService uploadService) {
this.uploadService = uploadService;
}
private UploadService uploadService;
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public #ResponseBody String handleFileUpload(
#RequestParam("file") MultipartFile file,#RequestParam String a,#RequestParam String b,#RequestParam String c, #RequestParam String d,#RequestParam String e) throws Exception{
java.io.InputStream inputStream =null;
if (!file.isEmpty() && checkContentType(file.getContentType())) {
try {
DBObject dbObject = new BasicDBObject();
//populate DBObject
inputStream = file.getInputStream();
uploadService.uploadFile(inputStream,file.getOriginalFilename(),file.getContentType(),dbObject);
return "success";
} catch (Exception e) {
return "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage();
}
finally {
if(inputStream!=null) {
inputStream.close();
}
}
} else {
return "You failed to upload " + file.getOriginalFilename() + " as it is an invalid file.";
}
}
}
##### Unit Test Class for Controller
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {
PresentationConfiguration.class,
MockDomainConfiguration.class})
#WebAppConfiguration
public class PDFUploadControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private UploadService uploadService;
private MockMvc mockMvc;
#Autowired
private ObjectMapper mapper;
private RestDocumentationResultHandler document;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
}
#After
public void resetMocks() {
reset(uploadService);
}
#Test
public void testHandleFileUpload() throws Exception {
FileInputStream fileInputStream = null;
MockMultipartFile mockMultipartFile = null;
try {
File file = new File("//Users//olatom//Desktop//testFile4Upload.pdf");
// create FileInputStream object
fileInputStream = new FileInputStream(file);
System.out.println("# File input stream for PDF : " + fileInputStream);
byte fileContent[] = new byte[(int) file.length()];
// Reads up to certain bytes of data from this input stream into an array of bytes.
fileInputStream.read(fileContent);
//create string from byte array
String pdfContent = new String(fileContent);
//mockMultipartFile = new MockMultipartFile("upload", file.getName(), "multipart/form-data", fileInputStream);
mockMultipartFile = new MockMultipartFile("file", fileInputStream);
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "265001916915724");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
//mockMvc.perform(fileUpload("/upload")
// .file(mockMultipartFile)
// .param("a", "1234").param("b", "PX1234").param("c", "100").param("d", "120")
// .contentType(MediaType.MULTIPART_FORM_DATA))
// .andExpect(status().isOk());
// mockMvc.perform(fileUpload("/upload")).andExpect(status().isOk());
//mockMvc.perform(fileUpload("/upload").file(mockMultipartFile)).andExpect(status().isOk());
mockMvc.perform(
fileUpload("/upload")
.content(mockMultipartFile.getBytes())
.param("a", "1234").param("b", "PX1234").param("c", "100").param("d", "120")
.contentType(mediaType)
)
.andExpect(status().isOk());
} catch (FileNotFoundException e) {
System.out.println("File not found" + e);
} catch (IOException ioe) {
System.out.println("IO Exception while reading file " + ioe);
} catch (Exception exc) {
} finally {
// close the streams using close method
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}
}
####### MockDomainConfiguration #####
/**
* Create Mockito mocks for the service classes.
* For this to work the #EnableAutoConfiguration annotation below also has to exclude JPA Autoconfiguration.
*/
#Configuration
#EnableAutoConfiguration()
public class MockDomainConfiguration {
#Bean
public UploadService mockUploadService() {
return mock(UploadService.class);
}
}
## MY ERROR
When I run the junit test in Intellij I get the following error:
2016-06-09 19:03:03,331 4170 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - DispatcherServlet with name '' processing POST request for [/upload]
2016-06-09 19:03:03,342 4181 [main] DEBUG o.s.b.a.e.m.EndpointHandlerMapping - Looking up handler method for path /upload
2016-06-09 19:03:03,343 4182 [main] DEBUG o.s.b.a.e.m.EndpointHandlerMapping - Did not find handler method for [/upload]
2016-06-09 19:03:03,343 4182 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /upload
2016-06-09 19:03:03,344 4183 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]
2016-06-09 19:03:03,344 4183 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'PDFUploadController'
2016-06-09 19:03:03,352 4191 [main] DEBUG o.s.w.s.m.m.a.ServletInvocableHandlerMethod - Error resolving argument [0] [type=org.springframework.web.multipart.MultipartFile]
HandlerMethod details:
Controller [x.y.z.rest.controller.PDFUploadController]
Method [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]
org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:251)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:96)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:99)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at x.y.z.rest.controller.PDFUploadControllerTest.testHandleFileUpload(PDFUploadControllerTest.java:140)
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:497)
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)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
2016-06-09 19:03:03,353 4192 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
2016-06-09 19:03:03,354 4193 [main] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
2016-06-09 19:03:03,354 4193 [main] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
2016-06-09 19:03:03,355 4194 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
2016-06-09 19:03:03,355 4194 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Successfully completed request
2016-06-09 19:03:03,359 4198 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext#646be2c3 testClass = PDFUploadControllerTest, testInstance = x.y.z.rest.controller.PDFUploadControllerTest#2b44d6d0, testMethod = testHandleFileUpload#PDFUploadControllerTest, testException = java.lang.AssertionError: Status expected:<200> but was:<400>, mergedContextConfiguration = [WebMergedContextConfiguration#797badd3 testClass = PDFUploadControllerTest, locations = '{}', classes = '{class x.y.z.rest.PresentationConfiguration, class x.y.z.rest.controller.MockDomainConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null], method annotated with #DirtiesContext [false] with mode [null].
2016-06-09 19:03:03,359 4198 [main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext#646be2c3 testClass = PDFUploadControllerTest, testInstance = x.y.z.rest.controller.PDFUploadControllerTest#2b44d6d0, testMethod = testHandleFileUpload#PDFUploadControllerTest, testException = java.lang.AssertionError: Status expected:<200> but was:<400>, mergedContextConfiguration = [WebMergedContextConfiguration#797badd3 testClass = PDFUploadControllerTest, locations = '{}', classes = '{class x.y.z.rest.PresentationConfiguration, class x.y.z.rest.controller.MockDomainConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].
java.lang.AssertionError: Status
Expected :200
Actual :400
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:655)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at x.y.z.rest.controller.PDFloadControllerTest.testHandleFileUpload(PDFUploadControllerTest.java:146)
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:497)
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)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Your help will be most appreciated.