junit.framework.ComparisonFailure: table count expected [1] but was [95] - java

I'm new to spring and dbunit and have problem with testing my dao layer. The entry is inserted succsessfully, but test ends with failure. Could you help me, please?
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.epam.lab.marharytakhramtsova.javalab.task1.dao.TagDAO;
import com.epam.lab.marharytakhramtsova.javalab.task1.dto.Tag;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/spring-config.xml" })
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
public class TestTagDAO {
#Autowired
private TagDAO tagDAO;
#Test
#DatabaseSetup(value = "/TagDAOTest.xml")
#ExpectedDatabase(value= "/expectedData.xml")
public void testInsert() throws Exception {
Tag tagToInsert = new Tag(4, "insertedTag");
tagDAO.insert(tagToInsert);
}
}
TagDAOTest.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<tag tag_id = "3" tag_name="myTag3" />
</dataset>
expectedData.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<tag tag_id = "3" tag_name="myTag3" />
<tag tag_id = "4" tag_name="insertedTag" />
</dataset>
Here is failure trace
I would be very grateful for the help!

Try this
#Test
#DatabaseSetup(value = "/TagDAOTest.xml")
#ExpectedDatabase(assertionMode=DatabaseAssertionMode.NON_STRICT, value= "/expectedData.xml")
public void testInsert() throws Exception {
Tag tagToInsert = new Tag(4, "insertedTag");
tagDAO.insert(tagToInsert);
}

Related

How to use MockMvc and MockRestServiceServer in Java #SpringBootTest

I am attempting to write a #SpringBootTest which will both issue REST requests and mock responses. I want to do this because my spring application receives REST requests and in response it fetches information from another source using REST. I would like to trigger my application by initiating a REST GET (MockMvc), but would also like to mock the other source's response (MockRestServiceServer).
Here is a sanitized version of the test, with my application removed:
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#Slf4j
#ExtendWith(SpringExtension.class)
#SpringBootTest
#AutoConfigureMockMvc
class RestTest {
private static final String URI = "/my-test-uri";
private static final String RESPONSE = "my-response";
#Autowired
private MockMvc mockMvc;
#Test
void testRest() throws Exception {
log.info("Initiating request for GET {}", URI);
mockMvc.perform(get(URI))
.andExpect(status().isOk())
.andExpect(content().string(containsString(RESPONSE)));
}
#TestConfiguration
static class TestConfig {
#Primary
#Bean
public RestTemplateBuilder restTemplateBuilder() {
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
server.expect(requestTo(URI))
.andRespond(withSuccess(RESPONSE, MediaType.APPLICATION_JSON));
log.info("Mocking response to GET {}: {}", URI, RESPONSE);
RestTemplateBuilder mockBuilder = mock(RestTemplateBuilder.class);
when(mockBuilder.build()).thenReturn(restTemplate);
return mockBuilder;
}
}
}
The test fails because it does not receive the response defined in TestConfig.restTemplateBuilder. I am providing both the REST requestor (testRest() method) and the REST responder (TestConfig.restTemplateBuilder). What am I doing wrong?
Here's the failure:
Status expected:<200> but was:<404>
Expected :200
Actual :404
<Click to see difference>
java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at com.mycompany.RestTest.testRest(RestTest.java:54)
...
at java.base/java.lang.Thread.run(Thread.java:830)

Spring Controller gives me 404 status error

So I am attempting to write a basic Rest Controller in Spring Tool Suite with Spring annotations where I hit the endpoint "/health" and I receive the following message upon hitting the endpoint "Kafka Streaming App is healthy".
The only error I receive is the 404 status error when I check on the browser and I have already tried logging please help. I think the problem might be how I am calling the Controller in the Main Application class in Spring.
Main Application Class
package com.eds.kafka.streaming.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
//#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
//#Configuration
//#EntityScan(basePackages = {"com.eds.kafka.streaming.model"})
//#ComponentScan(basePackages = { "com.eds.kafka.streaming.service", "com.eds.kafka.streaming.util", "com.eds.kafka.streaming.config", "com.eds.kafka.streaming.controller"}) //"com.tmobile.eds.infosec.volt.encr",
#ComponentScan(basePackages = {"com.eds.kafka.streaming"})
#SpringBootApplication
public class KafkaStreamingAppContainerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamingAppContainerApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(KafkaStreamingAppContainerApplication.class);
}
}
Controller Class
package com.eds.kafka.streaming.controller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#EnableAutoConfiguration
#PropertySource("classpath:application-${spring.profiles.active}.properties")
#RestController
public class MainController {
#RequestMapping(method = RequestMethod.GET, value = "/health", produces = "application/json")
#ResponseBody
public ResponseEntity home() {
System.out.println("Controller being configured!");
return new ResponseEntity("Kafka Streaming App is Healthy", HttpStatus.OK);
}
}
Please let me know if you have any advice and if needed I can provide a zipped version of the project if that is needed just message me.

WS Soap Handler class never invoked

I am developing a Jax Ws and i want to add Soap Handler to use for WS authentication. A added a handler chain xml and a Soap Handler class but code never call the Soap Handler's method.I use JDK 8 and Tomcat 7. What can be the problem?
My handler chain xml as below:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE javaee:handler-chains>
<javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<javaee:handler-chain>
<javaee:handler>
<javaee:handler-class>com.vw.AuthHandler
</javaee:handler-class>
</javaee:handler>
</javaee:handler-chain>
</javaee:handler-chains>
My Soap Handler class a below:
import java.io.PrintStream;
import java.io.StringReader;
import java.util.Collections;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class AuthHandler implements SOAPHandler<SOAPMessageContext> {
private static PrintStream out = System.out;
#Override
public Set<QName> getHeaders() {
return Collections.emptySet();
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outboundProperty) {
System.out.println("Hello!");
return true;
}
return false;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
System.out.println("Hello!");
return false;
}
#Override
public void close(MessageContext context) {
System.out.println("Hello!");
}
}
My Service is as below:
import javax.ejb.Stateless;
import javax.jws.HandlerChain;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import services.LoginOps;
import utilies.LoginParameters;
#WebService
#HandlerChain (file = "handlers.xml")
#SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
public class LService {
#WebMethod
public LoginParameters callStr(String str
}
...

how to solve BeanCreationExceptrion error?

I try to develop some server program using spring4 and jackrabbit. When i test the Controller class using JUnit, BeanCreationExceptrion error is occurs. I think this error associated with autowired variable. help me. how to solve this problem?
This is head of my Controller class.
package kr.ac.jbnu.sql.soremore.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.IRDMLConverter;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.IRDMLRDFMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RDMLRDFException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import kr.ac.jbnu.sql.soremore.service.rdf.RDFConverter;
import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
// reference
// http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
#Controller
public class SoremoreController {
private static final int buffer_size = 1024;
static Logger logger = Logger.getLogger(SoremoreController.class.getName());
private static String fileName = "";
#Autowired
private ApplicationContext appContext = null;
#Autowired
private IRDMLConverter rdmlConverter = null;
#Autowired
private IRDMLRDFMgmt rdmlRDFMgmt = null;
#Autowired
private IRDMLDBMgmt rdmlDBMgmt = null;
#Autowired
private RDFConverter rdfConverter = null;
....
This is my test class.
package kr.ac.jbnu.sql.soremore.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
//#ContextConfiguration(locations = { "classpath:/soremore-servlet.xml" })
#ContextConfiguration(locations = { "/application-config.xml" })
public class SoremoreControllerTest {
#Autowired
SoremoreController soremoreController = null;
#Test
public void storeRDML() {
// String[] hwpmlPaths = { "resource/sample_rdml/예제 1.xml",
// "resource/sample_rdml/예제 2.xml",
// "resource/sample_rdml/예제 3.xml",
// "resource/sample_rdml/예제 4.xml",
// "resource/sample_rdml/예제 5.xml",
// "resource/sample_rdml/예제 6.xml",
// "resource/sample_rdml/예제 7.xml",
// "resource/sample_rdml/예제 8.xml",
// "resource/sample_rdml/예제 9.xml",
// "resource/sample_rdml/예제 10.xml" };
//
// for (String hwpmlPath : hwpmlPaths) {
// soremoreController.storeRDML(hwpmlPath);
// }
ArrayList<RDML> rdmls = loadTestRDML();
boolean isSuccessful = false;
for (RDML rdml : rdmls) {
try {
soremoreController.storeRDML(rdml);
System.out.println();
isSuccessful = true;
} catch (Exception e) {
e.printStackTrace();
isSuccessful = false;
}
}
Assert.assertTrue(isSuccessful);
}
#Test
public void storeRDMLWithTraceability() throws IOException {
List<RDML>rdmls = null ;
String previousRDMLId = "xxx";
for (RDML rdml : rdmls) {
soremoreController.storeRDMLWithTraceability(rdml,
previousRDMLId, TraceabilityTypes.satisfy);
}
}
#Test
public void updateRDMLWithTraceability() {
String previousRDMLId1 = "xxx";
String previousRDMLId2 = "xxx";
String updatedTraceability = soremoreController.updateRDMLTraceability(
previousRDMLId1, previousRDMLId2, TraceabilityTypes.satisfy);
}
#Test
public void deleteRDMLWithTraceability() {
String previousRDMLId1 = "xxx";
String previousRDMLId2 = "xxx";
String removedTraceability = soremoreController.deleteRDMLTraceability(
previousRDMLId1, previousRDMLId2);
}
#Test
public void searchRDML() {
String rdmlKeyWord = "abc";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void searchRDML0() {
String rdmlKeyWord = "def";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void searchRDML1() {
String rdmlKeyWord = "2차년도계획서";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void getRDML() {
String rdmlID = "abc";
RDML rdml = soremoreController.getRDML(rdmlID);
}
#Test
public void getParentIDs() {
String rdmlID = "abcd";
ArrayList<String> parentIDs = soremoreController.getParentIDs(rdmlID);
for (String string : parentIDs) {
}
}
#Test
public void getChildIDs() {
String rdmlID = "abcd";
ArrayList<String> childIDs = soremoreController.getChildIDs(rdmlID);
for (String string : childIDs) {
}
}
public void getDirectLinkedTraceability() {
String rdmlID = "abcd";
ArrayList<Traceability> linkedTraceabilities = soremoreController
.getDirectLinkedTraceability(rdmlID);
for (Traceability traceability : linkedTraceabilities) {
}
}
public ArrayList<RDML> loadTestRDML() {
ArrayList<RDML> rdmls = new ArrayList<RDML>();
String xmlSource = "resource/sample_rdml";
File sourceDir = new File(xmlSource);
File[] sourceFiles = sourceDir.listFiles();
for (File file : sourceFiles) {
RDML rdml = new RDML();
rdml.setRdmlAsDocument(createDocument(file));
rdmls.add(rdml);
}
return rdmls;
}
private Document createDocument(File rdmlPathAsFile) {
SAXBuilder jdomBuilder = new SAXBuilder();
Document jdomDocument = null;
try {
jdomDocument = jdomBuilder.build(rdmlPathAsFile);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jdomDocument;
}
}
This is my spring configuration xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="kr.ac.jbnu.sql.soremore" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
<!-- for file upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="20000000" />
</bean>
</beans>
This is head of class of one variable.
package kr.ac.jbnu.sql.soremore.service.rdml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
import javax.xml.parsers.ParserConfigurationException;
import kr.ac.jbnu.sql.soremore.controller.SoremoreController;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import org.springframework.stereotype.Service;
#Service
public class RDMLDBMgmtImpl implements IRDMLDBMgmt {
static Logger logger = Logger.getLogger(SoremoreController.class.getName());
static private int docNumber = 0;
private Repository repository;
private Session session;
....
This is stacktrace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: kr.ac.jbnu.sql.soremore.controller.SoremoreController kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest.soremoreController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: kr.ac.jbnu.sql.soremore.controller.SoremoreController kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest.soremoreController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1261)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1009)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
... 28 more
In order for Spring to autowire the SoremoreController field in your test case it needs a bean definition in the ApplicationContext for a bean of that type. That means you need to component-scan the package (or a parent package) where the SoremoreController is defined in the xml file you point out in the ContextConfiguration annotation.
Note that all autowired fields in SoremoreController instance must also have corresponding beans defined in the ApplicationContext, otherwise Spring will not be able to create that instance, causing your test to fail with stacktraces similar to the one you posted (but always explicitly pointing out - towards the end - the root cause of the problem).

Spring MVC Junit testing MultipartFile always empty

I'm using spring-mvc version 4.1.6-RELEASE with Junit 4.12 and java 1.7, I have a controller for file uploading who works when I've tested it on server with Browser. But when I try to test it with junit the mockfilemultipart is always empty and I'm sure isn't so in the test class.
This is my servlet-context.xml
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- beans:import resource="../controller-context.xml"/-->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<context:component-scan base-package="it.isfol.iweb" />
This is the controller
package it.isfol.iweb.controller.pianoattivita;
import it.isfol.iweb.bean.wrappers.PianoAttivitaWrapper;
import it.isfol.iweb.controller.common.IsfolController;
import it.isfol.iweb.exceptions.IWebFatalException;
import it.isfol.iweb.service.pianoattivita.FilePianoAttivitaService;
import it.isfol.iweb.util.SessionConstant;
import java.util.Arrays;
import java.util.Collection;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
#Controller
public class UploadPianoAttivitaController extends IsfolController {
/**
*
*/
private static final long serialVersionUID = 5455170192118107020L;
private static final String UPLOAD_PAGE = "upload/upload";
private final Logger logger = LoggerFactory.getLogger(UploadPianoAttivitaController.class);
#Autowired
private FilePianoAttivitaService filePianoAttivitaService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String uploadHomePage(HttpSession session) {
logger.info("I'm home");
return goToUploadPage(session);
}
#RequestMapping(value = "/uploadInit", method = RequestMethod.GET)
public String uploadPageRedirect(HttpSession session) {
logger.info("redirect into upload");
return goToUploadPage(session);
}
#RequestMapping(value = "/uploadPiano", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String upload(#RequestParam("files[]") MultipartFile[] files, HttpSession session) throws IWebFatalException {
logger.debug("Writing file to disk...");
try {
Collection<PianoAttivitaWrapper> piani = filePianoAttivitaService.getPianoAttivitaWrapperFromFiles(Arrays.asList(files), session.getId());
session.setAttribute(SessionConstant.PIANO_ATTIVITA_LIST_WRAPPER, piani);
} catch (IWebFatalException e) {
throw e;
} catch (Throwable t) {
logger.error(t.getLocalizedMessage(), t);
throw new IWebFatalException(t);
}
return "pianoAttivita";
}
private String goToUploadPage(HttpSession session) {
logger.debug("redirect on upload page");
sessionHelper.clearSessionPianoReference(session);
return UPLOAD_PAGE;
}
public void setFilePianoAttivitaService(FilePianoAttivitaService filePianoAttivitaService) {
this.filePianoAttivitaService = filePianoAttivitaService;
}
}
Then my abstract class for testing
package it.isfol.iweb;
import java.io.IOException;
import java.util.Properties;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#WebAppConfiguration(value = "src/main/webapp")
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml", "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
public abstract class IsfolIwebTester extends AbstractJUnit4SpringContextTests {
private final Logger logger = LoggerFactory.getLogger(IsfolIwebTester.class);
private Properties testProperties = new Properties();
#Autowired
private WebApplicationContext webapp;
protected MockMvc mockMvc;
#Before
public void setup() {
logger.debug("reading properties");
try {
testProperties.load(this.getClass().getResourceAsStream("/test-conf.properties"));
this.mockMvc = MockMvcBuilders.webAppContextSetup(webapp).build();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (Throwable e) {
logger.error(e.getLocalizedMessage(), e);
}
}
public String getProperty(String key) {
return testProperties.getProperty(key);
}
}
and finally the test class who extends the class above
package it.isfol.iweb.pianoattivita;
import it.isfol.iweb.IsfolIwebTester;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
public class FilePianoAttivitaTester extends IsfolIwebTester {
private final Logger logger = LoggerFactory.getLogger(FilePianoAttivitaTester.class);
#Test
public void testRunning() {
logger.debug("Test started");
try {
String originalFile = getProperty("test.file.pianoattivita.path");
String originalName = FilenameUtils.getName(originalFile);
byte[] content = IOUtils.toByteArray(getClass().getResourceAsStream(originalFile));
MockMultipartFile file = new MockMultipartFile("testJunit", originalName, null, content);
this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/uploadPiano").file(file)).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().equals("pianoAttivita");
this.mockMvc.perform(MockMvcRequestBuilders.get("/pianoAttivita")).andExpect(MockMvcResultMatchers.view().name("upload/upload"));
} catch(Throwable t) {
logger.error(t.getLocalizedMessage(), t);
Assert.fail();
}
}
}
In the method upload of UploadPianoAttivitaController when I run Junit the param files[] contain 1 empty MultiPartFile, while when I run it on server and I upload a file from page everything is ok.
The name of your RequestParam for files must match with the MockMultipartFile name.
In your case is "files []" and in the mock is "testJunit", you can watch your HttpServletRequest params in your controller.
Try this way:
MockMultipartFile mockMultipartFile = new MockMultipartFile("file",
"OriginalName.txt",
"text/plain",
rateExceptionsFile);
mockMvc.perform(multipart(BASE_PATH + "/uploadFile")
.file(mockMultipartFile)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk());

Categories

Resources