Testcontainers could not find a valid Docker env - spring-boot

Running testcontainers leads to failed initialization.
Config class:
#ActiveProfiles("test")
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
#ContextConfiguration(initializers = {Postgres.Initializer.class})
#SpringBootTest
#Transactional
#Sql("classpath: schema.sql")
public abstract class IntegrationTestConfig {
#Autowired
protected ApplicationContext applicationContext;
#BeforeAll
static void startContainer(){
Postgres.CONTAINER.start();
}
}
Initializer class:
#UtilityClass
public class Postgres {
public static final PostgreSQLContainer CONTAINER = new PostgreSQLContainer("postgres:14.0");
public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
#Override
public void initialize(ConfigurableApplicationContext applicationContext) {
TestPropertyValues.of(
"spring.datasource.url=" + CONTAINER.getJdbcUrl(),
"spring.datasource.username=" + CONTAINER.getUsername(),
"spring.datasource.password=" + CONTAINER.getPassword()
).applyTo(applicationContext);
}
}
}
ommiting simple test classes for brievety, I catch:
Blockquoteork.test.context.support.AbstractContextLoader - Did not detect default resource location for test class /**/.IntegrationTestConfig]: class path resource [//IntegrationTestConfigContext.groovy] does not exist
11:08:22.594 [Test worker] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [*//.IntegrationTestConfig]: no resource found for suffixes {-context.xml, Context.groovy}.
11:08:22.596 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [/**/IntegrationTestConfig]: IntegrationTestConfig does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
11:08:22.825 [Test worker] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/home/user///Application.class]
11:08:22.827 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found #SpringBootConfiguration *//Application for test class /**/RepositoryTest
11:08:22.983 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [//tRepositoryTest]: using defaults.
11:08:22.984 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
11:08:22.994 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [javax/servlet/ServletContext]
11:08:23.005 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#1f641fb7, org.springframework.test.context.event.ApplicationEventsTestExecutionListener#69dc7b24, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#297454f7, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#602b7944, org.springframework.test.context.support.DirtiesContextTestExecutionListener#5f8d4b51, org.springframework.test.context.transaction.TransactionalTestExecutionListener#55821edf, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#5e5a2b74, org.springframework.test.context.event.EventPublishingTestExecutionListener#658098a2, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#50628080, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#155318b5, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#1add90e0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#7bf94e91, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener#3fdbb7ee, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#32c08610]
11:08:23.010 [Test worker] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#11939a9f testClass = RepositoryTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [ReactiveWebMergedContextConfiguration#229d508c testClass = RepositoryTest, locations = '{}', classes = '{class *//Application}', contextInitializerClasses = '*/**/Postgres$Initializer]', activeProfiles = '{test}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#1a10c47e, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#4816c0b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#33e50ff2, [ImportsContextCustomizer#5e83298e key = [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#27261190, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#67d5ac2f, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#6029f2a4, org.springframework.boot.test.web.reactive.server.WebTestClientContextCustomizer#5bb97fe7, org.springframework.boot.test.context.SpringBootTestArgs#1, org.springframework.boot.test.context.SpringBootTestWebEnvironment#7e19755a], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with #DirtiesContext [false] with mode [null].
11:08:23.105 [Test worker] DEBUG org.testcontainers.utility.TestcontainersConfiguration - Testcontainers configuration overrides will be loaded from file:/home/user/.testcontainers.properties
11:08:23.140 [Test worker] WARN org.testcontainers.utility.TestcontainersConfiguration - Attempted to read Testcontainers configuration file at file:/home/user/.testcontainers.properties but the file was not found. Exception message: FileNotFoundException: /home/user/.testcontainers.properties (No such file or directory)
11:08:23.151 [Test worker] INFO org.testcontainers.dockerclient.DockerMachineClientProviderStrategy - docker-machine executable was not found on PATH ([/app/bin, /usr/bin])
11:08:23.151 [Test worker] DEBUG org.testcontainers.dockerclient.RootlessDockerClientProviderStrategy - $XDG_RUNTIME_DIR is set but '/run/user/1000/docker.sock' does not exist.
11:08:23.152 [Test worker] DEBUG org.testcontainers.dockerclient.RootlessDockerClientProviderStrategy - '/home/user/.docker/run' does not exist.
11:08:23.220 [Test worker] DEBUG org.testcontainers.dockerclient.RootlessDockerClientProviderStrategy - '/run/user/1000/docker.sock' does not exist.
11:08:23.224 [Test worker] DEBUG org.testcontainers.dockerclient.DockerClientProviderStrategy - UnixSocketClientProviderStrategy: failed with exception InvalidConfigurationException (Could not find unix domain socket). Root cause NoSuchFileException (/var/run/docker.sock)
11:08:23.224 [Test worker] ERROR org.testcontainers.dockerclient.DockerClientProviderStrategy - Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
11:08:23.224 [Test worker] ERROR org.testcontainers.dockerclient.DockerClientProviderStrategy - UnixSocketClientProviderStrategy: failed with exception InvalidConfigurationException (Could not find unix domain socket). Root cause NoSuchFileException (/var/run/docker.sock)
11:08:23.224 [Test worker] ERROR org.testcontainers.dockerclient.DockerClientProviderStrategy - As no valid configuration was found, execution cannot continue
I tried to switch tc versions: 1.16.2 \1,1.15.3 . I checked user privileges - I already start docker w/o sudo. I also checked postgres image - both 14.0 inside the docker and tc initializer. What else I could try to solve the problem?

Well, Ive found out that java cant see files located into /var/run, so I remembered that I used flatpack for installation which turns out to be isolated environment for idea . Reinstalled traditionally idea works flawlessly.

Related

Difficulty in configuring consumer side contract cloud tests

I'm trying to use spring cloud contract to test my REST API. I'm following the instructions described is this tutorial https://cloud.spring.io/spring-cloud-contract/
I'm writing my single base test class using groovy.
My Rest Controller class:
#RestController
#RequestMapping(headers = arrayOf("X-API-Version=v2"))
class FileControllerV2(val storageService: StorageService) {
#PostMapping("/contracts.upload")
fun upload(#RequestParam file: MultipartFile, principal: Principal): FileNameResponse {
return storageService.save(file, principal.name)
}
#GetMapping("/contracts.download/{filename:.+}")
fun download(#PathVariable filename: String): ResponseEntity<*> {
return storageService.download(filename)
}
#GetMapping("/contracts.info/{filename:.+}")
fun info(#PathVariable filename: String): ResponseEntity<*> {
return storageService.info(filename)
}
}
My Contract Stub
package contracts.upload
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'POST'
url '/contracts.upload'
multipart(
file: named(
name: $(c(regex(nonEmpty())), p('filename')),
content: $(c(regex(nonEmpty())), p('content'))),
principal : $(regex('.+'))
)
headers {
contentType('multipart/form-data; boundary=----WebKitFormBoundaryBTX23kTw0Z5a5bsF')
header('X-API-Version','v2')
}
}
response {
status 200
body([
filename: 'filename'
])
headers {
contentType('application/json')
}
}
}
And my Base class:
class UploadBase extends Specification {
private StorageService storageService = Mock()
def setup() {
given:
RestAssuredMockMvc.standaloneSetup(new FileControllerV2(storageService))
}
}
And after building I've got following stacktrace
15:49:59.550 [Test worker] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
15:49:59.554 [Test worker] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
15:49:59.554 [Test worker] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
15:49:59.681 [Test worker] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking for request mappings in application context: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5c4dadd7
15:49:59.712 [Test worker] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - 3 request handler methods found on class com.project.fstorage.storage.FileControllerV2: {public org.springframework.http.ResponseEntity com.project.fstorage.storage.FileControllerV2.download(java.lang.String)={[/contracts.download/{filename:.+}],methods=[GET],headers=[X-API-Version=v2]}, public com.project.fstorage.response.FileNameResponse com.project.fstorage.storage.FileControllerV2.upload(org.springframework.web.multipart.MultipartFile,java.security.Principal)={[/contracts.upload],methods=[POST],headers=[X-API-Version=v2]}, public org.springframework.http.ResponseEntity com.project.fstorage.storage.FileControllerV2.info(java.lang.String)={[/contracts.info/{filename:.+}],methods=[GET],headers=[X-API-Version=v2]}}
15:49:59.723 [Test worker] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/contracts.download/{filename:.+}],methods=[GET],headers=[X-API-Version=v2]}" onto public org.springframework.http.ResponseEntity<?> com.project.fstorage.storage.FileControllerV2.download(java.lang.String)
15:49:59.725 [Test worker] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/contracts.upload],methods=[POST],headers=[X-API-Version=v2]}" onto public com.project.fstorage.response.FileNameResponse com.project.fstorage.storage.FileControllerV2.upload(org.springframework.web.multipart.MultipartFile,java.security.Principal)
15:49:59.725 [Test worker] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/contracts.info/{filename:.+}],methods=[GET],headers=[X-API-Version=v2]}" onto public org.springframework.http.ResponseEntity<?> com.project.fstorage.storage.FileControllerV2.info(java.lang.String)
15:49:59.994 [Test worker] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
15:49:59.995 [Test worker] INFO org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.5.Final
15:50:00.015 [Test worker] DEBUG org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
15:50:00.016 [Test worker] DEBUG org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
15:50:00.025 [Test worker] DEBUG org.hibernate.validator.internal.engine.ConfigurationImpl - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
15:50:00.026 [Test worker] DEBUG org.hibernate.validator.internal.engine.ConfigurationImpl - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy36
15:50:00.028 [Test worker] DEBUG org.hibernate.validator.internal.xml.ValidationXmlParser - Trying to load META-INF/validation.xml for XML based Validator configuration.
15:50:00.029 [Test worker] DEBUG org.hibernate.validator.internal.xml.ResourceLoaderHelper - Trying to load META-INF/validation.xml via TCCL
15:50:00.029 [Test worker] DEBUG org.hibernate.validator.internal.xml.ResourceLoaderHelper - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
15:50:00.030 [Test worker] DEBUG org.hibernate.validator.internal.xml.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only.
15:50:00.068 [Test worker] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5c4dadd7
15:50:00.096 [Test worker] DEBUG org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Looking for exception mappings: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5c4dadd7
15:50:00.113 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Initializing servlet ''
15:50:00.122 [Test worker] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
15:50:00.122 [Test worker] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
15:50:00.125 [Test worker] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
15:50:00.125 [Test worker] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
15:50:00.125 [Test worker] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,systemProperties,systemEnvironment]
15:50:00.125 [Test worker] INFO org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
15:50:00.125 [Test worker] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
15:50:00.127 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
15:50:00.127 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using LocaleResolver [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#186a2f7]
15:50:00.128 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using ThemeResolver [org.springframework.web.servlet.theme.FixedThemeResolver#71cabba8]
15:50:00.128 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using RequestToViewNameTranslator [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#53aff6f3]
15:50:00.128 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using FlashMapManager [org.springframework.web.servlet.support.SessionFlashMapManager#5138be3e]
15:50:00.128 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
15:50:00.128 [Test worker] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 3 ms
15:50:00.128 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Servlet '' configured successfully
15:50:00.175 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - DispatcherServlet with name '' processing POST request for [/contracts.upload]
15:50:00.177 [Test worker] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking up handler method for path /contracts.upload
15:50:00.179 [Test worker] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Did not find handler method for [/contracts.upload]
15:50:00.179 [Test worker] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/contracts.upload] in DispatcherServlet with name ''
15:50:00.179 [Test worker] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request
Condition not satisfied:
response.statusCode == 200
| | |
| 404 false
io.restassured.module.mockmvc.internal.MockMvcRestAssuredResponseImpl#77920871
Condition not satisfied:
response.statusCode == 200
| | |
| 404 false
io.restassured.module.mockmvc.internal.MockMvcRestAssuredResponseImpl#77920871
at org.springframework.cloud.contract.verifier.tests.UploadSpec.validate_shouldSaveFile(UploadSpec.groovy:25)
I don't know what can be the cause of not recognising these endpoints.
Edited
I've added generated tests
package org.springframework.cloud.contract.verifier.tests
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import com.project.fstorage.UploadBase
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
class UploadSpec extends UploadBase {
def validate_shouldSaveFile() throws Exception {
given:
def request = given()
.header("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryBTX23kTw0Z5a5bsF")
.header("X-API-Version", "v2")
.multiPart('file', 'filename', 'content'.bytes)
.param('principal', 'レ')
when:
def response = given().spec(request)
.post("/contracts.upload")
then:
response.statusCode == 200
response.header('Content-Type') ==~ java.util.regex.Pattern.compile('application/json.*')
and:
DocumentContext parsedJson = JsonPath.parse(response.body.asString())
assertThatJson(parsedJson).field("['filename']").isEqualTo("filename")
}
}
In case of using Security it's better to set up the normal context to rest assured or add the filter manually.
Example of setting up the web application context
#Autowired
private WebApplicationContext context;
#Before
public void setup() {
RestAssuredMockMvc.webAppContextSetup(context);
}

Error testing spring boot 1.4 application

I have very simple spring boot 1.4 application with one rest controller. When i tried to test the context loading of this i am getting error like below :-
13:29:03.623 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.628 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:29:03.632 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
13:29:03.641 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
13:29:03.644 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.650 [main] DEBUG o.s.b.t.c.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]: using defaults.
13:29:03.659 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
13:29:03.667 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
13:29:03.671 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
13:29:03.672 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#2db7a79b, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#6950e31, org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener#b7dd107, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#42eca56e, org.springframework.test.context.support.DirtiesContextTestExecutionListener#52f759d7, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#7cbd213e, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#192d3247, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#3ecd23d9, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#569cfc36]
13:29:03.674 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.674 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.690 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.690 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.691 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.691 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.692 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.692 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.695 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#67b467e9 testClass = FrontendServiceApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#47db50c5 testClass = FrontendServiceApplicationTests, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
13:29:03.696 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.696 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.697 [main] DEBUG o.s.t.c.s.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext#67b467e9 testClass = FrontendServiceApplicationTests, testInstance = com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests#548ad73b, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#47db50c5 testClass = FrontendServiceApplicationTests, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]]].
13:29:03.699 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener#b7dd107] to prepare test instance [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests#548ad73b]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener.prepareTestInstance(AutoConfigureReportTestExecutionListener.java:49)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
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)
Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with #ContextConfiguration or #ContextHierarchy.
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:91)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 24 common frames omitted
13:29:03.705 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext#67b467e9 testClass = FrontendServiceApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#47db50c5 testClass = FrontendServiceApplicationTests, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
test class is :-
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class FrontendServiceApplicationTests {
#Test
public void contextLoads() {
}
}
And application class is :-
#SpringBootApplication
#ImportResource({"classpath:dbContext.xml", "classpath:dbClientMappingContext.xml"})
public class FrontendServiceApplication {
/**
* The main method.
*
* #param args the arguments
*/
public static void main(String[] args) {
SpringApplication.run(FrontendServiceApplication.class, args);
}
}
What i am doing wrong here?
It looks like Spring Boot cannot find your #SpringBootApplication class using classpath scanning.
So give the following a try:
#RunWith(SpringRunner.class)
#SpringBootTest(
classes = FrontendServiceApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT
)
public class FrontendServiceApplicationTests {
#Test
public void contextLoads() {
}
}

spring batch ItemWriter creating output twice

I have written a spring batch job which reads from a db and then write to a csv.
The job is pretty simple and it works HOWEVER the ItemWriter looks like it is being executed twice. i.e. I am ending up with two CSV's (exactly the same), instead of one.
Can someone help me work out why please? It does so with a different jobExecution.id.
Attaching batch job and console output of run below...
#Configuration
#EnableBatchProcessing
public class ExportMasterListCsvJobConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public Job exportMasterListCsvJob(
Step readStgDbAndExportMasterListStep,
Step writeToCsvStep) {
return jobBuilderFactory.get("exportMasterListCsvJob")
.incrementer(new RunIdIncrementer())
.flow(readStgDbAndExportMasterListStep)
.end()
.build();
}
#Bean
public Step readStgDbAndExportMasterListStep(
#Value("${exportMasterListCsv.generateMasterListRows.chunkSize}") int chunkSize,
#Qualifier("queryOnlineStagingDbReader") ItemReader<MasterList> queryOnlineStagingDbReader,
#Qualifier("masterListFileWriter") ItemWriter<MasterList> masterListFileWriter) {
return stepBuilderFactory.get("readStgDbAndExportMasterListStep")
.<MasterList,MasterList>chunk(chunkSize)
.reader(queryOnlineStagingDbReader)
.writer(masterListFileWriter)
.build();
}
#Bean
public ItemReader<MasterList> queryOnlineStagingDbReader(
DataSource onlineStagingDb,
#Value("${exportMasterListCsv.generateMasterListRows.masterListSql}") String masterListSql) {
JdbcCursorItemReader<MasterList> reader = new JdbcCursorItemReader<>();
reader.setDataSource(onlineStagingDb);
reader.setSql(masterListSql);
reader.setRowMapper(new RowMapper<MasterList>() {
#Override
public MasterList mapRow(ResultSet resultSet, int i) throws SQLException {
MasterList masterList = new MasterList();
masterList.setL2(resultSet.getString("l2"));
masterList.setL2Name(resultSet.getString("l2_name"));
return masterList;
}
});
return reader;
}
#Bean
#StepScope
public ItemWriter<MasterList> masterListFileWriter(
FileSystemResource masterListFile,
#Value("#{stepExecutionContext}")Map<String, Object> executionContext) {
FlatFileItemWriter<MasterList> writer = new FlatFileItemWriter<>();
writer.setResource(masterListFile);
DelimitedLineAggregator<MasterList> lineAggregator = new DelimitedLineAggregator<>();
lineAggregator.setDelimiter(",");
BeanWrapperFieldExtractor<MasterList> extractor = new BeanWrapperFieldExtractor<MasterList>();
extractor.setNames(new String[] { "l2", "l2Name"});
lineAggregator.setFieldExtractor(extractor);
writer.setLineAggregator(lineAggregator);
writer.setForceSync(true);
writer.open(new ExecutionContext(executionContext));
return writer;
}
#Bean
#JobScope
public FileSystemResource masterListFile(
#Value("${temp.dir}") String tempDir,
#Value("#{jobExecution.id}") Long jobId
) throws IOException {
return new FileSystemResource(new File(tempDir, "masterList" + jobId + ".csv"));
}
}
And Console Output...
13:03:45.815 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.827 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:03:45.836 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
13:03:45.853 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest] from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
13:03:45.884 [main] DEBUG org.springframework.test.context.support.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#3cbbc1e0 declaringClass = 'com.myer.pricing.onlinestore.export.ExportMasterListCsvTest', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
13:03:45.899 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]: class path resource [com/myer/pricing/onlinestore/export/ExportMasterListCsvTest-context.xml] does not exist
13:03:45.900 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]: class path resource [com/myer/pricing/onlinestore/export/ExportMasterListCsvTestContext.groovy] does not exist
13:03:45.900 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]: no resource found for suffixes {-context.xml, Context.groovy}.
13:03:45.927 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.boot.test.IntegrationTestPropertiesListener#724af044, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#4678c730, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#6767c1fc, org.springframework.test.context.support.DirtiesContextTestExecutionListener#29ee9faa, org.springframework.test.context.transaction.TransactionalTestExecutionListener#c038203, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#cc285f4]
13:03:45.931 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.931 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.946 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.946 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.948 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.948 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.950 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.950 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.953 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#6a4f787b testClass = ExportMasterListCsvTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
13:03:45.954 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.954 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.959 [main] DEBUG org.springframework.test.util.ReflectionTestUtils - Getting field 'mergedContextConfiguration' from target object [[DefaultTestContext#6a4f787b testClass = ExportMasterListCsvTest, testInstance = com.myer.pricing.onlinestore.export.ExportMasterListCsvTest#53b32d7, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]] or target class [class org.springframework.test.context.support.DefaultTestContext]
13:03:45.960 [main] DEBUG org.springframework.test.util.ReflectionTestUtils - Setting field 'propertySourceProperties' of type [null] on target object [[MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]] or target class [class org.springframework.test.context.MergedContextConfiguration] to value [[Ljava.lang.String;#4667ae56]
13:03:45.961 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext#6a4f787b testClass = ExportMasterListCsvTest, testInstance = com.myer.pricing.onlinestore.export.ExportMasterListCsvTest#53b32d7, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.IntegrationTest=true}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]].
13:03:46.072 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
13:03:46.073 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
13:03:46.074 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
13:03:46.074 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [test] PropertySource with highest search precedence
13:03:46.075 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [integrationTest] PropertySource with search precedence immediately lower than [systemEnvironment]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.6.RELEASE)
2016-07-22 13:03:46.541 INFO 10084 --- [ main] c.m.p.o.export.ExportMasterListCsvTest : Starting ExportMasterListCsvTest on IGSM473537 with PID 10084 (C:\design_centre_dev\myer-pricing-engine\java-onlinestore-feed-exporter\target\test-classes started by rriviere in C:\design_centre_dev\myer-pricing-engine\java-onlinestore-feed-exporter)
2016-07-22 13:03:46.542 INFO 10084 --- [ main] c.m.p.o.export.ExportMasterListCsvTest : The following profiles are active: batchtest
2016-07-22 13:03:46.875 INFO 10084 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e08711f: startup date [Fri Jul 22 13:03:46 AEST 2016]; root of context hierarchy
2016-07-22 13:03:48.151 INFO 10084 --- [ main] o.s.b.f.config.PropertiesFactoryBean : Loading properties file from URL [jar:file:/C:/.m2/repository/org/springframework/integration/spring-integration-core/4.2.8.RELEASE/spring-integration-core-4.2.8.RELEASE.jar!/META-INF/spring.integration.default.properties]
2016-07-22 13:03:48.157 INFO 10084 --- [ main] o.s.i.config.IntegrationRegistrar : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2016-07-22 13:03:48.716 WARN 10084 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-07-22 13:03:48.728 WARN 10084 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-07-22 13:03:48.742 INFO 10084 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2016-07-22 13:03:48.751 INFO 10084 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2016-07-22 13:03:48.900 INFO 10084 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$402d705e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-07-22 13:03:49.060 INFO 10084 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-07-22 13:03:49.459 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [db/sql/staging_db.sql]
2016-07-22 13:03:49.465 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [db/sql/staging_db.sql] in 6 ms.
2016-07-22 13:03:49.710 WARN 10084 --- [ main] o.s.b.c.l.AbstractListenerFactoryBean : org.springframework.batch.item.ItemWriter is an interface. The implementing class will not be queried for annotation based listener configurations. If using #StepScope on a #Bean method, be sure to return the implementing class so listner annotations can be used.
2016-07-22 13:03:49.797 INFO 10084 --- [ main] o.s.aop.framework.CglibAopProxy : Unable to proxy method [public final java.lang.String org.springframework.core.io.FileSystemResource.getPath()] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.
2016-07-22 13:03:50.236 INFO 10084 --- [ main] o.s.b.f.config.PropertiesFactoryBean : Loading properties file from URL [jar:file:/C:/.m2/repository/org/springframework/integration/spring-integration-core/4.2.8.RELEASE/spring-integration-core-4.2.8.RELEASE.jar!/META-INF/spring.integration.default.properties]
2016-07-22 13:03:50.730 INFO 10084 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
2016-07-22 13:03:51.258 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-07-22 13:03:51.281 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 23 ms.
2016-07-22 13:03:51.813 INFO 10084 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2016-07-22 13:03:51.814 INFO 10084 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2016-07-22 13:03:51.814 INFO 10084 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'application:batchtest.errorChannel' has 1 subscriber(s).
2016-07-22 13:03:51.814 INFO 10084 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
2016-07-22 13:03:51.832 INFO 10084 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2016-07-22 13:03:51.844 INFO 10084 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-07-22 13:03:51.973 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-07-22 13:03:52.044 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] launched with the following parameters: [{run.id=1}]
2016-07-22 13:03:52.073 INFO 10084 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [readStgDbAndExportMasterListStep]
2016-07-22 13:03:52.167 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-07-22 13:03:52.169 INFO 10084 --- [ main] c.m.p.o.export.ExportMasterListCsvTest : Started ExportMasterListCsvTest in 6.091 seconds (JVM running for 6.895)
2016-07-22 13:03:52.196 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] launched with the following parameters: [{random=93853}]
2016-07-22 13:03:52.234 INFO 10084 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [readStgDbAndExportMasterListStep]
2016-07-22 13:03:52.290 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] completed with the following parameters: [{random=93853}] and the following status: [COMPLETED]
2016-07-22 13:03:52.305 INFO 10084 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e08711f: startup date [Fri Jul 22 13:03:46 AEST 2016]; root of context hierarchy
2016-07-22 13:03:52.307 INFO 10084 --- [ Thread-1] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0
2016-07-22 13:03:52.308 INFO 10084 --- [ Thread-1] o.s.i.endpoint.EventDrivenConsumer : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2016-07-22 13:03:52.309 INFO 10084 --- [ Thread-1] o.s.i.channel.PublishSubscribeChannel : Channel 'application:batchtest.errorChannel' has 0 subscriber(s).
2016-07-22 13:03:52.309 INFO 10084 --- [ Thread-1] o.s.i.endpoint.EventDrivenConsumer : stopped _org.springframework.integration.errorLogger
2016-07-22 13:03:52.314 INFO 10084 --- [ Thread-1] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
2016-07-22 13:03:52.317 INFO 10084 --- [ Thread-1] o.s.j.d.e.EmbeddedDatabaseFactory : Shutting down embedded database: url='jdbc:hsqldb:mem:testdb'
And this produces two CSV's each with a different jobExecution.id which I have appended to the file name. masterList0.csv AND masterList1.csv
thanks in advance
I had the following setting in my yml file...
spring:
batch:
job.enabled: true
This was causing my job to run twice. After changing it to false it fixed my problem.

Could not detect default configuration classes for test class with Kotlin and #AutoConfigureMockMvc

I'm giving Kotlin a whirl and was converting the test below that was running fine in Java to Kotlin. After converting the test using the IntelliJ conversion tool I tried to run it but I got this error:
22:32:19.476 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.test.app.web.DeveloperControllerTest]
22:32:19.486 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
22:32:19.494 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
22:32:19.517 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.test.app.web.DeveloperControllerTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
22:32:19.539 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.test.app.web.DeveloperControllerTest], using SpringBootContextLoader
22:32:19.543 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.test.app.web.DeveloperControllerTest]: class path resource [com/test/app/web/DeveloperControllerTest-context.xml] does not exist
22:32:19.544 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.test.app.web.DeveloperControllerTest]: class path resource [com/test/app/web/DeveloperControllerTestContext.groovy] does not exist
22:32:19.544 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.test.app.web.DeveloperControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
22:32:19.545 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.test.app.web.DeveloperControllerTest]: DeveloperControllerTest does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
java.lang.StackOverflowError
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:964)
at java.lang.reflect.WeakCache.containsValue(WeakCache.java:175)
at java.lang.reflect.Proxy.isProxyClass(Proxy.java:791)
at java.lang.reflect.Proxy.getInvocationHandler(Proxy.java:815)
at sun.reflect.annotation.AnnotationInvocationHandler.asOneOfUs(AnnotationInvocationHandler.java:226)
at sun.reflect.annotation.AnnotationInvocationHandler.equalsImpl(AnnotationInvocationHandler.java:201)
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:64)
at com.sun.proxy.$Proxy13.equals(Unknown Source)
at java.util.HashMap.putVal(HashMap.java:634)
at java.util.HashMap.put(HashMap.java:611)
at java.util.HashSet.add(HashSet.java:219)
at org.springframework.boot.test.context.ImportsContextCustomizer$ContextCustomizerKey.collectElementAnnotations(ImportsContextCustomizer.java:239)
at org.springframework.boot.test.context.ImportsContextCustomizer$ContextCustomizerKey.collectClassAnnotations(ImportsContextCustomizer.java:226)
Java test:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class DeveloperControllerTest {
#Autowired
private MockMvc mvc;
#Test
public void createNewDeveloper() throws Exception {
mvc.perform(
post("/api/v1/developers")
.param("username", "boaty")
.param("email", "boaty#mcboatface.org")
.param("password", "123loveboats")
.param("passwordConfirmation", "123loveboats")
).andExpect(status().isCreated());
}
}
Converted to Kotlin:
#RunWith(SpringRunner::class)
#SpringBootTest
#AutoConfigureMockMvc
class DeveloperControllerTest {
#Autowired
lateinit var mvc: MockMvc
#Test
#Throws(Exception::class)
fun createNewDeveloper() {
mvc.perform(
post("/api/v1/developers")
.param("username", "boaty")
.param("email", "boaty#mcboatface.org")
.param("password", "123loveboats")
.param("passwordConfirmation", "123loveboats"))
.andExpect(status().isCreated)
}
}
What I've noticed with this is that if I remove the annotation AutoConfigureMockMvc Spring will boot and try to run, but it'll fail because it can't autowire MockMvc.
I'm using Kotlin 1.0.1-2 together with Spring Boot 1.4.0-M2.
try adding
#ComponentScan(basePackages = arrayOf("YourAppBasePackage"))
#SpringBootTest(classes = arrayOf(MyExampleApplication::class))
This solved the issue for me
The stack overflow is occurring when Spring Boot attempts to introspect the annotations on DeveloperControllerTest.
DeveloperControllerTest is annotated with kotlin.Metadata. Metadata is annotated with kotlin.annotation.Retention. Retention is annotated with kotlin.annotation.Target and Target is annotated with itself. Target being annotated with itself is the cause of the stack overflowing.
It is legal, although probably quite unusual, for an annotation to be used to annotate itself. Spring Boot should probably be more defensive.

HttpRequestMethodNotSupportedException: Request method 'POST' not supported

Creating a unit test with MockMvc I am running into:
HttpRequestMethodNotSupportedException: Request method 'POST' not supported
Which causes the test case to fail expecting a '200' but getting a '405'. Some of the additional things you may see in the Junit are for Spring Rest Docs and can be ignored. Such as the #Rule or the .andDo() on the mockMvc Call. I have followed the following documentation Spring Rest Docs - Path Parameter and cannot seem to get it working.
Here is the Controller:
#RestController("/transferObjects")
public class TransferObjectController {
#RequestMapping(method=RequestMethod.GET, produces="application/json")
public List<TransferObject> getTransferObjects(){
// do some magic
return null;
}
#RequestMapping(value = "/{name}", method=RequestMethod.POST)
#ResponseStatus(HttpStatus.OK)
public void addTransferObject(#PathVariable("name")String name){
// do magic
}
#RequestMapping(value = "/{name}", method=RequestMethod.DELETE)
#ResponseStatus(HttpStatus.OK)
public void deleteTransferObject(#PathVariable("name")String name){
// do magic
}
Here is the Junit Class:
public class TransferObjectControllerTest {
#Rule
public RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(new TransferObjectController())
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
#Test
public void testAddTransferObject() throws Exception {
this.mockMvc.perform(post("/transferObjects/{name}", "hi"))
.andExpect(status().isOk()).andDo(document("transferObject",
pathParameters(
parameterWithName("name").description("The name of the new Transfer Object to be created."))));
}
And here is the console while running the test:
11:20:48.148 [main] INFO o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5ab785fe
11:20:48.205 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Looking for exception mappings: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5ab785fe
11:20:48.283 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Initializing servlet ''
11:20:48.307 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
11:20:48.307 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
11:20:48.312 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
11:20:48.312 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
11:20:48.313 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,systemProperties,systemEnvironment]
11:20:48.313 [main] INFO o.s.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
11:20:48.313 [main] INFO o.s.t.w.s.TestDispatcherServlet - FrameworkServlet '': initialization started
11:20:48.318 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
11:20:48.318 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using LocaleResolver [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#63238bf4]
11:20:48.318 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using ThemeResolver [org.springframework.web.servlet.theme.FixedThemeResolver#32b97305]
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using RequestToViewNameTranslator [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#2d2e6747]
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using FlashMapManager [org.springframework.web.servlet.support.SessionFlashMapManager#417e7d7d]
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
11:20:48.319 [main] INFO o.s.t.w.s.TestDispatcherServlet - FrameworkServlet '': initialization completed in 6 ms
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Servlet '' configured successfully
11:20:48.361 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - DispatcherServlet with name '' processing POST request for [/transferObjects/hi]
11:20:48.364 [main] DEBUG o.s.t.w.s.s.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking up handler method for path /transferObjects/hi
11:20:48.368 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
11:20:48.369 [main] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
11:20:48.369 [main] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
11:20:48.369 [main] WARN o.s.web.servlet.PageNotFound - Request method 'POST' not supported
11:20:48.370 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
11:20:48.370 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Successfully completed request
It appears I was able to fix this problem.
Taking a closer look at the console while running the test I noticed:
Mapped "{[],methods=[GET],produces=[application/json]}" onto public java.util.List<common.to.TransferObject> sf.common.controller.TransferObjectController.getTransferObjects()
Mapped "{[/{name}],methods=[POST]}" onto public void sf.common.controller.TransferObjectController.addTransferObject(java.lang.String)
Mapped "{[/{name}],methods=[DELETE]}" onto public void sf.common.controller.TransferObjectController.deleteTransferObject(java.lang.String)
this shows that it is mapping the controller request mappings to the specific RequestMapping the method holds. #RestController("/transferObjects") is not actually defining the mapping as a parent. For me to do that I must include #RequestMapping("/transferObjects") underneath the #RestController.
So by changing the parent mapping I can now use the following test case:
#Test
public void testAddTransferObject() throws Exception {
this.mockMvc.perform(post("/transferObjects/{name}", "hi"))
.andExpect(status().isOk()).andDo(document("transferObject",
pathParameters(
parameterWithName("name").description("The name of the new Transfer Object to be created."))));
}

Resources