Test spring with MockMvc - java

I'm trying to run a "integration test" with Spring and Junit, but i'm getting this error:
java.lang.AssertionError: Authentication should not be null
My classes:
Application.java
#SpringBootApplication
#ComponentScan
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
SecurityConfig.java
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public AuthenticationFilter authenticationFilterBean() throws Exception {
final AuthenticationFilter authenticationFilter = new AuthenticationFilter();
authenticationFilter.setAuthenticationManager(this.authenticationManagerBean());
return authenticationFilter;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.POST, "/users").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
LoginTests.java
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {Application.class})
#WebAppConfiguration
#TestExecutionListeners(value = DbUnitTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
#DatabaseSetup("classpath:dbunit/User.xml")
public class LoginTests {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext context;
#Resource
private AuthenticationFilter authenticationFilter;
#Test
public void login() throws Exception {
final LoginRequest loginRequest = new LoginRequest();
loginRequest.setEmail(EMAIL);
loginRequest.setPassword(PASSWORD);
mockMvc.perform(post(ENDPOINT)
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(loginRequest))
).andExpect(authenticated());
}
Error:
java.lang.AssertionError: Authentication should not be null
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
at org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers$AuthenticatedMatcher.match(SecurityMockMvcResultMatchers.java:98)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at br.com.bla.studying.integration.LoginTests.login(LoginTests.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: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.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)
If i test with postman, everything works fine.
Any idea?

Related

How can I test IntegrationFlow with Jms.messageDrivenChannelAdapter

I tried to test IntegrationFlow which receives JMS message, then do some logic, send it to another JMS queue and then save it to the file.
I have such flow:
public class ProcessingFlow {
#Bean
public IntegrationFlow jmsProcessingFlow(
ActiveMQConnectionFactory activeMQConnectionFactory,
ValidationService validationService,
ConverterService converterService,
JmsMessageSender jmsMessageSender,
#Value("${folder.location}") String folderLocation) {
return IntegrationFlows.from(Jms.messageDrivenChannelAdapter(activeMQConnectionFactory).destination("JMSQueueFrom").id("jmsProcessing"))
.<String>handle((incomeFilePayload, messageHeaders) -> {
validationService.validate(incomeFilePayload);
String message = converterService.convert(incomeFilePayload);
jmsMessageSender.sendMessage("JMSQueueTo", message);
return incomeFilePayload;
})
.handle(Files.outboundAdapter(new File(folderLocation))
.fileNameGenerator("file.xml"))
.get();
}
}
I wrote such integration test:
#RunWith(SpringRunner.class)
#SpringIntegrationTest
#SpringBootTest(classes = {ProcessingFlowIntegrationTest.TestConfig.class})
#ActiveProfiles("test")
#DirtiesContext
public class ProcessingFlowIntegrationTest {
#MockBean
private ValidationService validationService;
#SpyBean
private ConverterService converterService;
#Autowired
private MockIntegrationContext mockIntegrationContext;
#After
public void tearDown() {
this.mockIntegrationContext.resetBeans();
}
#Test
public void shouldTestProcessingFlow() throws Exception {
TextMessage message = mock(TextMessage.class);
when(message.getText()).thenReturn(XmlContentEnum.CONTENT.getContent());
this.mockIntegrationContext.substituteMessageSourceFor("jmsProcessing", MockIntegration.mockMessageSource(message));
verify(validationService).validate(eq(message.getText()));
verify(converterService).convert(eq(message.getText()));
}
#TestConfiguration
#Import(value = {
ProcessingFlow.class,
JmsConfiguration.class,
TestConfig.class
})
static class TestConfig {
}
}
But after running I received such exception:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'jmsProcessing' is expected to be of type 'org.springframework.integration.endpoint.SourcePollingChannelAdapter' but was actually of type 'org.springframework.integration.jms.JmsMessageDrivenEndpoint'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:399)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:215)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:157)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:142)
at com.postpunk.flows.integration.ProcessingFlowIntegrationTest.shouldTestProcessingFlow(ProcessingFlowIntegrationTest.java:57)
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:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
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.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:366)
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$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
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$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
As I understood from exception my bean has type "org.springframework.integration.jms.JmsMessageDrivenEndpoint", but mockIntegrationContext expected "org.springframework.integration.endpoint.SourcePollingChannelAdapter". Does anybody know how can I test JmsMessageDrivenEndpoint correctly and what I did wrong?
Set noAutoStartup for the message-driven endpoint on the #SpringIntegrationTest.
Autowire the IntegrationFlow.
Then flow.getInputChannel().send(...);

Spring unit testing - Failed to load ApplicationContext

hi i'm new with unit testing and when u tried to test my spring application, i can't resolve this probleme Failed to load application context. Can not find the path [which I specified in #ContextConfiguration]
here my code :
-Application context :
#Configuration
#EnableWebMvc
#ComponentScan("com.RealEstate")
#Import(ApplicationContext.class)
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**")
.addResourceLocations("classpath:/images/").setCachePeriod(31556926);
registry.addResourceHandler("/Resources/**")
.addResourceLocations("/Resources/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry){
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
registry.viewResolver(internalResourceViewResolver);
}
}
and here's my test class :
#RunWith( SpringJUnit4ClassRunner.class )
#ContextConfiguration(classes = { WebConfig.class})
public class CustomerDaoImplTest {
#Autowired
CustomerDao customerDao;
#BeforeClass
public static void setUp(){
// MockitoAnnotations.initMocks(customerDao);
}
#Test
public void findById(){
//Assert.assertNotNull(adminDao.readAdminById(1));
//Assert.assertNull(adminDao.readAdminById(3));
Assert.assertNull(null);
}
#Test
public void saveCustomer(){
//customerDao.storeCustomer(getSampleCustomer());
//Assert.assertEquals(customerDao.getCustomersList().size(), 7);
Assert.assertEquals(5+2, 7);
}
#Test
public void deleteCustomer(){
customerDao.deleteCustomer("customer1");
Assert.assertEquals(customerDao.getCustomersList().size(), 5);
}
#Test
public void deleteEmployeeByInvalidSsn(){
customerDao.deleteCustomer("23423");
Assert.assertEquals(customerDao.getCustomersList().size(), 6);
}
#Test
public void findAllEmployees(){
Assert.assertEquals(customerDao.getCustomersList().size(), 6);
}
#Test
public void findEmployeeByUsername(){
Assert.assertNotNull(customerDao.readCustomerByUsername("overflow"));
Assert.assertNull(customerDao.readCustomerByUsername("paul"));
}
public Customer getSampleCustomer(){
Customer customer = new Customer();
customer.setId(7);
customer.setName("ihab");
customer.setLastName("benamer");
customer.setEmail("benamer#gmail.com");
customer.setUsername("ihab");
try{
customer.setBirthday(new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse("1996-11-10").getTime()));
} catch (java.text.ParseException e){
;
}
customer.setIdNumber("987521");
customer.setAddress("consantine, algérie");
customer.setPassword("123");
customer.setPhone("+213557665392");
customer.setSex("male");
return customer;
}
}
I have a structure like this:
java
|com.RealEstate
|config
|dao
|model
|service
|controller
test
|com.RealEstate
|config
|dao
here's the error slack
saveAdmin(com.RealEstate.dao.AdminDaoImplTest) Time elapsed: 0 sec <<< ERROR!
java.lang.NullPointerException
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:227)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping.registerHandlers(StandaloneMockMvcBuilder.java:480)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.registerMvcSingletons(StandaloneMockMvcBuilder.java:346)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.initWebAppContext(StandaloneMockMvcBuilder.java:331)
at org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder.build(AbstractMockMvcBuilder.java:127)
at com.RealEstate.dao.AdminDaoImplTest.setUp(AdminDaoImplTest.java:66)
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.RunBefores.evaluate(RunBefores.java:24)
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.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
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.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

SpringWS Junit Test Exception: No endpoint can be found for request [SaajSoapMessage

I am getting an exception when I try to run the Spring Web Service JUnit Test Using the Spring WebService ServerSide Integration Test using MockWebServiceClient. When I run the WebService Junit Test, I'm getting an exception:
No endpoint can be found for request [SaajSoapMessagehttp://schemas.xmlsoap.org/soap/envelope/}Envelope]
Spring_WS_ServletConfig
#Configuration
#EnableWs
#EnableTransactionManagement
// #ComponentScan({ "com.springws.endpoint", "com.mybatis.", "com.mapstruct" })
// #ImportResource({ "classpath:/SpringConfig/spring-database-config.xml" })
public class Spring_WS_ServletConfig extends WsConfigurerAdapter {
#Bean("StudentServiceWsdl")
public DefaultWsdl11Definition orders() throws SQLException {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("StudentService_SpringWS_PortType");
definition.setLocationUri("http://localhost:8080/MvnSpringMcc/StudentService_SpringWS/");
definition.setTargetNamespace("com.springws.student/LearnSpringWs");
definition.setServiceName("SpringWSService");
// definition.setWsdl(new
// ClassPathResource("/wsdl/StudentService.wsdl"));
definition.setSchema(studentsSchema());
return definition;
}
#Bean
public XsdSchema studentsSchema() {
Resource resource = new ClassPathResource("/wsdl/StudentTask.xsd");
return new SimpleXsdSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validator = new PayloadValidatingInterceptor();
validator.setValidateRequest(true);
validator.setValidateResponse(true);
validator.setSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
}
TestConfig
#Configuration
#ComponentScan({ "com.springws.test", "com.mybatis.mapper.vo", "com.mybatis.service", "com.mapstruct.mapper",
"com.springws.endpoint", "com.mybatis.mapper" })
//#Import(Spring_WS_ServletConfig.class)
#ImportResource({ "classpath:testResources/spring-ws-test-database-config.xml" })
public class TestConfig {
}
CourseServiceEndPointServerSideIntegrationTest
#EnableTransactionManagement
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { TestConfig.class, Spring_WS_ServletConfig.class })
public class CourseServiceEndPointServerSideIntegrationTest {
#Autowired
ResourceLoader resourceLoader;
#Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
#Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
}
#Test
public void courseEndpoint() throws Exception {
Resource requestPayLoad = resourceLoader.getResource("classpath:xmlTestFiles/RequestPayLoad.xml");
Resource responsePayLoad = resourceLoader.getResource("classpath:xmlTestFiles/ResponsePayLoad.xml");
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
}
}
RequestPayLoad.xml File
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:lear="com.springws.student/LearnSpringWs" xmlns:stud="com.springws.student/StudentSchema">
<soapenv:Header />
<soapenv:Body>
<lear:GetCourseRequest>
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
</soapenv:Body>
</soapenv:Envelope>
Exception
CourseServiceEndpoint(com.springws.endpoint.CourseServiceEndpoint) Time elapsed: 0.219 sec <<< FAILURE!
java.lang.AssertionError: No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
at org.springframework.ws.test.support.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.ws.test.server.MockWebServiceClient.sendRequest(MockWebServiceClient.java:184)
at com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest.courseEndpoint(CourseServiceEndPointServerSideIntegrationTest.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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.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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Failed tests: CourseServiceEndpoint(com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest): No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
The better way to solve this problem is to change for proper methods in RequestCreators
and ResponseMatchers for SOAP one.
import static org.springframework.ws.test.server.RequestCreators.withSoapEnvelope;
import static org.springframework.ws.test.server.ResponseMatchers.soapEnvelope;
Changes need to be done in our test method.
Before:
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
After:
mockClient.sendRequest(withSoapEnvelope(requestPayLoad)).andExpect(soapEnvelope(responsePayLoad));
Finally I was able to solve the problem: Just provide the Soap Payload Information in the MockWebServiceClient.sendRequest's withPayload() & andExpect(payload()) methods.
RequestPayLoad.xml
<lear:GetCourseRequest xmlns:lear="com.springws.student/LearnSpringWs"
xmlns:stud="com.springws.student/StudentSchema">
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
ResponsePayLoad.xml
<ns3:GetCourseResponse xmlns:ns2="com.springws.student/StudentSchema"
xmlns:ns3="com.springws.student/LearnSpringWs">
<ns3:Course>
<ns2:courseID>100</ns2:courseID>
<ns2:courseName>Physics</ns2:courseName>
<ns2:courseCategory>Physics</ns2:courseCategory>
<ns2:credit>3.0</ns2:credit>
</ns3:Course>
</ns3:GetCourseResponse>

Can't add application.prop to Camel test

I can't make my test use application.propperies in test envirement while on main it works fine. Write that it cant find such a propperty. I tried to use #TestPropertySource(locations="classpath:application.properties") but didn't help. Also added application.propperies to resource in test folder.
My project structure
My test class:
#RunWith(SpringRunner.class)
#SpringBootTest
//#TestPropertySource(locations="classpath:application.properties")
public class Excercise5to7ApplicationTests extends CamelTestSupport {
#Override
protected RouteBuilder createRouteBuilder() {
return new MyRoute();
}
#Before
public void mockEndpoints() throws Exception {
AdviceWithRouteBuilder mockKafka = new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
// mock the for testing
interceptSendToEndpoint("kafka:*")
.skipSendToOriginalEndpoint()
.to("mock:kafka");
}
};
RouteDefinition myRoute = context.getRouteDefinition("myRoute");
myRoute.adviceWith(context, mockKafka);
}
#Test
public void testWithRealFile() throws Exception {
context.start();
MockEndpoint kafka = getMockEndpoint("mock:kafka");
kafka.expectedMessageCount(10);
kafka.assertIsSatisfied();
context.stop();
}
#Override
protected Context createJndiContext() throws Exception {
JndiContext context = new JndiContext();
context.bind("myBean", new MyBean());
return context;
}
#Override
public boolean isUseAdviceWith() {
return true;
}
}
The exception itself:
org.apache.camel.RuntimeCamelException: java.lang.IllegalArgumentException: Property with key [route.from.path] not found in properties from text: file:{{route.from.path}}?noop=true
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1774)
at org.apache.camel.model.RouteDefinitionHelper.initRouteInputs(RouteDefinitionHelper.java:380)
at org.apache.camel.model.RouteDefinitionHelper.prepareRouteImp(RouteDefinitionHelper.java:298)
at org.apache.camel.model.RouteDefinitionHelper.prepareRoute(RouteDefinitionHelper.java:270)
at org.apache.camel.model.RoutesDefinition.route(RoutesDefinition.java:205)
at org.apache.camel.model.RoutesDefinition.from(RoutesDefinition.java:158)
at org.apache.camel.builder.RouteBuilder.from(RouteBuilder.java:169)
at com.bisnode.excercise5to7.Routes.MyRoute.configure(MyRoute.java:16)
at org.apache.camel.builder.RouteBuilder.checkInitialized(RouteBuilder.java:462)
at org.apache.camel.builder.RouteBuilder.configureRoutes(RouteBuilder.java:402)
at org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:383)
at org.apache.camel.impl.DefaultCamelContext$1.call(DefaultCamelContext.java:971)
at org.apache.camel.impl.DefaultCamelContext$1.call(DefaultCamelContext.java:968)
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3108)
at org.apache.camel.impl.DefaultCamelContext.addRoutes(DefaultCamelContext.java:968)
at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:352)
at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:262)
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.RunBefores.evaluate(RunBefores.java:24)
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.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalArgumentException: Property with key [route.from.path] not found in properties from text: file:{{route.from.path}}?noop=true
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.getPropertyValue(DefaultPropertiesParser.java:271)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.readProperty(DefaultPropertiesParser.java:157)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.doParse(DefaultPropertiesParser.java:116)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.parse(DefaultPropertiesParser.java:100)
at org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:63)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:230)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:173)
at org.apache.camel.impl.DefaultCamelContext.resolvePropertyPlaceholders(DefaultCamelContext.java:2411)
at org.apache.camel.model.ProcessorDefinitionHelper.resolvePropertyPlaceholders(ProcessorDefinitionHelper.java:735)
at org.apache.camel.model.RouteDefinitionHelper.initRouteInputs(RouteDefinitionHelper.java:378)
... 48 more
I had the same issue loading a properties file in a Test and I overrode the protected method "useOverridePropertiesWithPropertiesComponent" available through CamelTestSupport class. For example:
#Override
protected Properties useOverridePropertiesWithPropertiesComponent()
{
Properties properties = new Properties();
try
{
properties.load(new FileInputStream(
"./src/test/resources/test.properties"));
}
catch (IOException e)
{
fail(e.getMessage());
}
return properties;
}
You can find more information here: https://camel.apache.org/manual/latest/using-propertyplaceholder.html
A shorter variant of #CookieSoup answer could be to update the Camel Context for properties component.
#RunWith(CamelSpringBootRunner.class)
#ContextConfiguration
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class YourRouterTest extends CamelTestSupport
{
...
#Override
protected CamelContext createCamelContext() throws Exception
{
SimpleRegistry registry = new SimpleRegistry();
registry.put("beanName", bean);
CamelContext camelContext = new DefaultCamelContext(registry);
camelContext.addRoutes(yourRoutes);
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:application.properties");
camelContext.addComponent("properties", pc);
return camelContext;
}
...
}

Spring could not obtain transaction-synchronized Session for current thread

I am trying to test a change password functionality in my spring application but i got an exception.
I have read similar problems here and tried to use them but they didn't help me. The problem occurs when I want to run the test class to test whether the a method for changing the password is working correctly. Here is my test class:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = UiApplication.class)
#WebAppConfiguration
public class SecurityServiceTest {
#Autowired
SecurityService securityService;
#Test
public void testLoginSuccess() {
securityService.login("user1", "pass1");
}
#Test(expected = BadCredentialsException.class)
public void testLoginFail() {
securityService.login("user1", "pass11");
}
#Test
public void testChangePwd(){
securityService.changePwd("user1", "pass1", "123", "123");
securityService.login("user1", "123");
}
}
The problem occured when I added the last test - testChangePwd(), before adding it was working properly.
UPDATE- the SecurityService is an interface and its implementation is the following class:
#Service
public class SecurityServiceImpl implements SecurityService {
private static Logger logger = Logger.getLogger(SecurityServiceImpl.class);
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private UserDaoImpl userDao;
#Override
public void login(String username, String password) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
logger.info(String.format("Auto login %s successfully!", username));
}
}
#Override
public void changePwd(String username, String password, String newPwd, String againPwd) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
if(newPwd.equals(againPwd))
userDao.findByUserName(username).setPassword(password);
}
}
}
Here is the exception:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at com.example.dao.impl.UserDaoImpl.findByUserName(UserDaoImpl.java:26)
at com.example.dao.impl.UserDaoImpl$$FastClassBySpringCGLIB$$94db05c6.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.example.dao.impl.UserDaoImpl$$EnhancerBySpringCGLIB$$59fce477.findByUserName(<generated>)
at com.example.auth.impl.SecurityServiceImpl.changePwd(SecurityServiceImpl.java:50)
at com.example.auth.SecurityServiceTest.testChangePwd(SecurityServiceTest.java:31)
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.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: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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Categories