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;
}
...
}
Related
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(...);
my test return failed with error:
java.lang.AssertionError: Content type not set
I read that this error don't mean so much, because return the same if there is a NPE or don't match the handler ...
But i don't understand where is the error, seem to me all ok ...
My controller is already with #RestController
This is controller Method:
#RestController
#RequestMapping("/local")
public class ControllerTest{
.....
#RequestMapping(value = "/test", method = RequestMethod.GET)
#ResponseBody
public JsonResponse<TestResponseModel> test (
#RequestParam(value = "data1", required = true) String data1,
#RequestParam(value = "data2", required = true) String data2,
{
try {
TestRequestModel input= new TestRequestModel();
input.setData1(data1);
input.setData2(data2);
TestResponseModel entities = business.test(input);
return JsonResponse(entities);
} catch (TestException e) {
log.error("APPLICATION EXCEPTION", e);
throw e;
} catch (Exception e) {
log.error("UNHANDLED EXCEPTION", e);
throw new TestException(e);
}
}
}
and this is the test:
#Mock
private Business business;
#Mock
private TestResponseModel testResponseModel;
#Test
public void getTest() throws Exception {
when(business.test(isA(TestRequestModel.class))).thenReturn(testResponseModel);
mockMvc.perform(get("/local/test")
.requestAttr("data1", "data1_test")
.requestAttr("data2", "data2_test"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
StackTrace:
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:35)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:65)
at org.springframework.test.web.servlet.result.ContentResultMatchers$1.match(ContentResultMatchers.java:82)
at org.springframework.test.web.servlet.MockMvc.applyDefaultResultActions(MockMvc.java:191)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:163)
at com.test.controller.TestClassTest.GetTest(TestClassTest.java:79)
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.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:68)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:74)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
I fixed changing in Test Unit .requestAttr() to .param()
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)
I have a class which produces screenshot:
#Component
public class ImagesHandlerImpl implements ImagesHandler {
....
public boolean doScreen() throws IOException, AWTException {
final Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
...
}
}
My app created with spring boot, and I need test it. But I get java.awt.HeadlessException
My test:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = ImagesHandlerImpl.class)
#ContextConfiguration(classes = App.class)
public class ImagesHandlerImplTest {
...
#Test
public void whenDoScreenThenFilenameLikeTemplate() throws IOException, AWTException {
imagesHandler.doScreen();
final String name = dir.listFiles()[0].getName();
assertThat("SCREEN_0", is(name));
}
}
I try to prevent HeadlessException:
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class);
builder.headless(false).run(args);
}
}
I use spring-boot version 1.5.6.RELEASE.
But it didn't help. I get log:
java.awt.HeadlessException at
sun.awt.HeadlessToolkit.getScreenSize(HeadlessToolkit.java:284) at
org.robinhood.image.ImagesHandlerImpl.doScreen(ImagesHandlerImpl.java:42)
at
org.robinhood.image.ImagesHandlerImplTest.whenDoScreenThenCreatePrintScreen(ImagesHandlerImplTest.java:51)
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.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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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)
Help me. How to fix this issue?
Thank You!
The spring test runner does not invoke the main method of App class.
And it will turn on Headless mode by default.
You can specify JVM argument -Djava.awt.headless=false for executing the test case.
Another solution is setting the property during bean initialization.
#Component
public class ImagesHandlerImpl implements ImagesHandler, InitializingBean {
#Override
public void afterPropertiesSet() throws Exception {
System.setProperty("java.awt.headless", "false");
}
public boolean doScreen() throws Exception {
//...
}
}
Add
// overcome #SpringBootTest setup
System.setProperty("java.awt.headless", "false")
before the doScreen() method invocation.
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?