Difficulty in configuring consumer side contract cloud tests - spring

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);
}

Related

Testcontainers could not find a valid Docker env

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.

how execute and show friendly tests output when running gradle from command line

I can run easily my project tests from IntelliJ IDEA but I am struggling to run them and see the results running from command line.
I read several suggestions around and it seems the trick part is over here
tasks.test {
useJUnitPlatform()
}
tasks.withType<Test> {
this.testLogging {
this.showStandardStreams = true
}
}
As you can see from bellow image all tests are ran and I can see the result in IntelliJ
Neverthelless, when I try from Windows Command Line in same project I get
C:\WSs\KotlinGradleIntelliJ\jokenpo>gradlew test
> Task :test
JokenpoApplicationTests STANDARD_OUT
13:19:28.436 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:19:28.452 [Test worker] 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:19:28.467 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.mycomp.jokenpo.JokenpoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
13:19:28.483 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.mycomp.jokenpo.JokenpoApplicationTests], using SpringBootContextLoader
13:19:28.498 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: class path resource [com/mycomp/jokenpo/JokenpoApplicationTests-context.xml] does not exist
13:19:28.498 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: class path resource [com/mycomp/jokenpo/JokenpoApplicationTestsContext.groovy] does not exist
13:19:28.498 [Test worker] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
13:19:28.498 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: JokenpoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
13:19:28.552 [Test worker] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.mycomp.jokenpo.JokenpoApplicationTests]
13:19:28.621 [Test worker] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\WSs\KotlinGradleIntelliJ\jokenpo\build\classes\kotlin\main\com\mycomp\jokenpo\JokenpoApplication.class]
13:19:28.621 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found #SpringBootConfiguration com.mycomp.jokenpo.JokenpoApplication for test class com.mycomp.jokenpo.JokenpoApplicationTests
13:19:28.738 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.mycomp.jokenpo.JokenpoApplicationTests]: using defaults.
13:19:28.739 [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.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.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]
13:19:28.757 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#1f9e5479, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#7f837ef0, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#75d05b, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#532b090b, org.springframework.test.context.support.DirtiesContextTestExecutionListener#3efba28b, org.springframework.test.context.transaction.TransactionalTestExecutionListener#5a6b3f5a, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#7432cb44, org.springframework.test.context.event.EventPublishingTestExecutionListener#7f5ae798, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#1cd6ed02, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#1f44802d, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#7d4e106a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#55004e7c, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#7e951723]
13:19:28.762 [Test worker] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#7d4abcae testClass = JokenpoApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#d073212 testClass = JokenpoApplicationTests, locations = '{}', classes = '{class com.mycomp.jokenpo.JokenpoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#4b3fa0b3, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#1a515c84, [ImportsContextCustomizer#672ec1ca key = [org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#51dd20fd, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#1a85aac8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#e2f4006e, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#9eb94ec], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]], class annotated with #DirtiesContext [false] with mode [null].
13:19:28.784 [Test worker] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.6.RELEASE)
2020-04-27 13:19:29.222 INFO 13608 --- [ Test worker] c.m.jokenpo.JokenpoApplicationTests : Starting JokenpoApplicationTests on SPANOT149 with PID 13608 (started by Cast in C:\WSs\KotlinGradleIntelliJ\jokenpo)
2020-04-27 13:19:29.222 INFO 13608 --- [ Test worker] c.m.jokenpo.JokenpoApplicationTests : No active profile set, falling back to default profiles: default
2020-04-27 13:19:30.008 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-04-27 13:19:30.070 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 64ms. Found 1 JPA repository interfaces.
2020-04-27 13:19:31.402 INFO 13608 --- [ Test worker] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2020-04-27 13:19:31.424 INFO 13608 --- [ Test worker] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-04-27 13:19:31.424 INFO 13608 --- [ Test worker] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]
2020-04-27 13:19:31.595 INFO 13608 --- [ Test worker] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-04-27 13:19:31.595 INFO 13608 --- [ Test worker] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2343 ms
2020-04-27 13:19:31.675 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-04-27 13:19:31.916 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-04-27 13:19:31.916 INFO 13608 --- [ Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-04-27 13:19:32.218 INFO 13608 --- [ Test worker] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-04-27 13:19:32.301 INFO 13608 --- [ Test worker] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-04-27 13:19:32.382 INFO 13608 --- [ Test worker] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-04-27 13:19:32.533 INFO 13608 --- [ Test worker] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-04-27 13:19:33.002 INFO 13608 --- [ Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-04-27 13:19:33.018 INFO 13608 --- [ Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default
2020-04-27 13:19:33.202 WARN 13608 --- [ Test worker] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-04-27 13:19:33.487 INFO 13608 --- [ Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:33.836 INFO 13608 --- [ Test worker] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring TestDispatcherServlet ''
2020-04-27 13:19:33.836 INFO 13608 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2020-04-27 13:19:33.851 INFO 13608 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 15 ms
2020-04-27 13:19:33.904 INFO 13608 --- [ Test worker] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 56309 (http) with context path ''
2020-04-27 13:19:33.904 INFO 13608 --- [ Test worker] c.m.jokenpo.JokenpoApplicationTests : Started JokenpoApplicationTests in 5.107 seconds (JVM running for 7.245)
UserServiceTest STANDARD_OUT
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.mycomp.jokenpo.UserServiceTest], using SpringBootContextLoader
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] o.s.t.c.support.AbstractContextLoader : Could not detect default resource locations for test class [com.mycomp.jokenpo.UserServiceTest]: no resource found for suffixes {-context.xml, Context.groovy}.
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.mycomp.jokenpo.UserServiceTest]: UserServiceTest does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found #SpringBootConfiguration com.mycomp.jokenpo.JokenpoApplication for test class com.mycomp.jokenpo.UserServiceTest
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.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.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.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]
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#2401a061, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#7ef022b4, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#5970e47d, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#3a26795d, org.springframework.test.context.support.DirtiesContextTestExecutionListener#130dd4d0, org.springframework.test.context.transaction.TransactionalTestExecutionListener#6c97b187, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#321ae364, org.springframework.test.context.event.EventPublishingTestExecutionListener#3bff88eb, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#46296010, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#17e3eadb, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#72872a80, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#35784ceb, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#38dc83b4]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.6.RELEASE)
2020-04-27 13:19:34.653 INFO 13608 --- [ Test worker] com.mycomp.jokenpo.UserServiceTest : Starting UserServiceTest on SPANOT149 with PID 13608 (started by Cast in C:\WSs\KotlinGradleIntelliJ\jokenpo)
2020-04-27 13:19:34.653 INFO 13608 --- [ Test worker] com.mycomp.jokenpo.UserServiceTest : No active profile set, falling back to default profiles: default
2020-04-27 13:19:34.858 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-04-27 13:19:34.858 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 1 JPA repository interfaces.
2020-04-27 13:19:35.005 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting...
2020-04-27 13:19:35.005 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
2020-04-27 13:19:35.037 INFO 13608 --- [ Test worker] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-04-27 13:19:35.037 INFO 13608 --- [ Test worker] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-04-27 13:19:35.081 INFO 13608 --- [ Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-04-27 13:19:35.081 INFO 13608 --- [ Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.378 WARN 13608 --- [ Test worker] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-04-27 13:19:35.500 INFO 13608 --- [ Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.679 INFO 13608 --- [ Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-04-27 13:19:35.738 INFO 13608 --- [ Test worker] com.mycomp.jokenpo.UserServiceTest : Started UserServiceTest in 1.11 seconds (JVM running for 9.072)
2020-04-27 13:19:35.754 INFO 13608 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.755 INFO 13608 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.755 INFO 13608 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.756 INFO 13608 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-27 13:19:35.756 INFO 13608 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.756 INFO 13608 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-27 13:19:35.759 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown initiated...
2020-04-27 13:19:35.759 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-04-27 13:19:35.765 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-04-27 13:19:35.765 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown completed.
BUILD SUCCESSFUL in 14s
4 actionable tasks: 1 executed, 3 up-to-date
C:\WSs\KotlinGradleIntelliJ\jokenpo>
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.2.6.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
kotlin("jvm") version "1.3.71"
kotlin("plugin.spring") version "1.3.71"
kotlin("plugin.jpa") version "1.3.71"
}
group = "com.mycomp"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
val developmentOnly by configurations.creating
configurations {
runtimeClasspath {
extendsFrom(developmentOnly)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("com.h2database:h2")
//runtimeOnly("org.hsqldb:hsqldb")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
testImplementation ("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<Test> {
this.testLogging {
this.showStandardStreams = true
}
}
Test file
package com.mycomp.jokenpo
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.mycomp.jokenpo.enums.PlayType
import com.mycomp.jokenpo.model.User
import com.mycomp.jokenpo.respository.UserRepository
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.web.util.NestedServletException
#AutoConfigureMockMvc
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ExtendWith(SpringExtension::class, MockitoExtension::class)
class JokenpoApplicationTests {
#Autowired
private lateinit var mockMvc: MockMvc
#MockBean
lateinit var respository: UserRepository
#BeforeEach
fun setup() {
whenever(respository.save(User(1, "Test", PlayType.LAGARTO))).thenAnswer {
it.arguments.first()
}
}
#Test
fun `Test createUser in the happy path scenario`() {
val user = User(1, "Test", PlayType.LAGARTO)
mockMvc.post("/users/") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(user)
accept = MediaType.APPLICATION_JSON
}.andExpect {
status { isOk }
content { contentType(MediaType.APPLICATION_JSON) }
content { json("""{"id":1,"name":"Test"}""") }
}
//verify(respository, times(1)).save(user)
}
#Test
fun `Test negative scenario of createUser`() {
val user = User(2, "Test", PlayType.LAGARTO)
assertThrows<NestedServletException> {
mockMvc.post("/users/") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(user)
accept = MediaType.APPLICATION_JSON
}
}
verify(respository, times(1)).save(user)
}
#Test
fun findUser() {
mockMvc.get("/users?id=99")
.andExpect {
status { isOk }
}
verify(respository, times(1)).findAll()
}
}
PS.: I don't see any change in output if I try "gradle clean test" or point the file with "gradle test --tests JokenpoApplicationTests"
I am confused if my tests are execcuted but I miss some Gradle configutarion to shw the result or even worst my tests aren't executed at all and I lost some basic concept because IntelliJ adds this automatically and "hide" from my eyes
When using the Gradle rich console, test execution is reported in the dynamic part of the Gradle output. This means that once test finishes, that output is gone.
By doing
this.testLogging {
this.showStandardStreams = true
}
you only redirect the test outputs to the console.
Instead, have a look at the TestLoggingContainer documentation and consider logging tests passing and failed with something like:
testLogging {
events "passed", "failed"
}

Wrong Header of the API versioning of the Post Request does not come to handleNoHandlerFoundException?

I am using Spring Boot v2.1.7 + HATEOAS + Spring Rest + Spring Security. When consumer doesn't pass the correct Custom Header in the request, say passes X-Accept-Version=v5, it gives me below error.
Error:
2020-03-26 15:44:48.201 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : POST "/employee-catalog-api/reference-types", parameters={}
2020-03-26 15:44:48.216 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-03-26 15:44:48.217 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] .m.c.d.m.p.s.SAMLUserIdentityServiceImpl : Trying to get UserId from Security Context
2020-03-26 15:44:48.224 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#5c85f23b
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Code:
#PostMapping(path = "/employee-types", headers = {X-Accept-Version=v1})
public ResponseEntity<Integer> saveEmployeeType(#Valid #RequestBody EmployeeDto employeeDto) {
.....
......
......
return new ResponseEntity<>(HttpStatus.OK);
}
Why its not coming to handleNoHandlerFoundException of the #ControllerAdvice ?
#Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
...................
return handleExceptionInternal(ex, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
}
I was able to solve this issue by taking a reference from : How to set default value of exported as false in rest resource spring data rest.
By adding below logic, it works greatly.
#Component
public class SpringRestConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setRepositoryDetectionStrategy(RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED);
config.setExposeRepositoryMethodsByDefault(false);
}
}

Spring Cloud Contract: Can the verifier Test not be run with SpringRunner.class ?

Hello I set up a basic Api Test like below:
#RunWith(SpringRunner.class)
#SpringBootTest
#WebAppConfiguration
#ActiveProfiles("test")
public abstract class BaseMockMvcSpec {
public static Logger log = LoggerFactory.getLogger(BaseMockMvcSpec.class);
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
#Autowired
FilterChainProxy springSecurityFilterChain;
#Autowired
UserRepository users;
#Autowired
PasswordEncoder passwordEncoder;
#Autowired
CustomClientDetailsService clientDetialsService;
#Mock SecurityContext mockSecurityContext;
#Before
public void setUp() {
RestAssuredMockMvc.standaloneSetup(new AccountDetailsController());
mvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity(springSecurityFilterChain))
.build();
BaseClientDetails testClient = new ClientBuilder("testclient")
.secret("testclientsecret")
.authorizedGrantTypes("password")
.scopes("read", "wirte")
.autoApprove(true)
.build();
clientDetialsService.addClient(testClient);
User user = createDefaultUser("testuser", passwordEncoder.encode("testpassword"), "max", "Mustermann", new Email("test#lokata.de"));
users.deleteAll();
users.save(user);
log.info("setup BaseMockMvcSpec");
}
public String oauth(){
String token = "notValidToken";
try {
token = validAccessToken();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Bearer " + token;
}
private String validAccessToken() throws Exception {
String username = "testuser";
String password = "testpassword";
MockHttpServletResponse response = mvc
.perform(post("/oauth/token")
.header("Authorization", "Basic "
+ new String(Base64Utils.encode(("testclient:testclientsecret")
.getBytes())))
.param("username", username)
.param("password", password)
.param("grant_type", "password"))
.andDo(print())
.andReturn().getResponse();
return new ObjectMapper()
.readValue(response.getContentAsByteArray(), OAuthToken.class)
.accessToken;
}
#JsonIgnoreProperties(ignoreUnknown = true)
private static class OAuthToken {
#JsonProperty("access_token")
public String accessToken;
}
}
I get the following output of the Test run:
2017-06-27 01:36:23.379 INFO 47446 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither #ContextConfiguration nor #ContextHierarchy found for test class [de.example.microservice.authservice.verifier.tests.OauthserviceTest], using SpringBootContextLoader
2017-06-27 01:36:23.379 INFO 47446 --- [ Test worker] o.s.t.c.support.AbstractContextLoader : Could not detect default resource locations for test class [de.example.microservice.authservice.verifier.tests.OauthserviceTest]: no resource found for suffixes {-context.xml, Context.groovy}.
2017-06-27 01:36:23.379 INFO 47446 --- [ Test worker] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [de.example.microservice.authservice.verifier.tests.OauthserviceTest]: OauthserviceTest does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
2017-06-27 01:36:23.383 INFO 47446 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found #SpringBootConfiguration de.example.microservice.authservice.AuthserverApplication for test class de.example.microservice.authservice.verifier.tests.OauthserviceTest
2017-06-27 01:36:23.385 INFO 47446 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener, 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.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]
2017-06-27 01:36:23.386 INFO 47446 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#2efec58d, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#65dbe1b, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#4d31ce57, org.springframework.test.context.support.DirtiesContextTestExecutionListener#750239e7, org.springframework.test.context.transaction.TransactionalTestExecutionListener#2d885867, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#464e86ab, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener#54eab43, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#6167770c, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#ec35027, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#3c0ae48a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#4cee44fb, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#166b957d, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#2bdadff]
2017-06-27 01:36:23.459 INFO 47446 --- [ Test worker] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2017-06-27 01:36:23.459 INFO 47446 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2017-06-27 01:36:23.462 INFO 47446 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 3 ms
2017-06-27 01:36:23.540 INFO 47446 --- [ Test worker] d.l.m.authservice.BaseMockMvcSpec : setup BaseMockMvcSpec
2017-06-27 01:36:23.564 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token']
2017-06-27 01:36:23.564 DEBUG 47446 --- [ Test worker] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2017-06-27 01:36:23.564 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : matched
2017-06-27 01:36:23.564 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-06-27 01:36:23.564 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#79e774c0
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'GET /logout
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/logout'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'PUT /logout
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'DELETE /logout
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 5 of 12 in additional filter chain; firing Filter: 'ClientCredentialsTokenEndpointFilter'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.w.a.www.BasicAuthenticationFilter : Basic Authentication Authorization header found for user 'testclient'
2017-06-27 01:36:23.565 DEBUG 47446 --- [ Test worker] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.s.w.a.www.BasicAuthenticationFilter : Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7e2b6867: Principal: org.springframework.security.core.userdetails.User#81d402dd: Username: testclient; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7e2b6867: Principal: org.springframework.security.core.userdetails.User#81d402dd: Username: testclient; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#b7217c5
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2017-06-27 01:36:23.567 DEBUG 47446 --- [ Test worker] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7e2b6867: Principal: org.springframework.security.core.userdetails.User#81d402dd: Username: testclient; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
2017-06-27 01:36:23.568 DEBUG 47446 --- [ Test worker] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#6b9626fc, returned: 1
2017-06-27 01:36:23.568 DEBUG 47446 --- [ Test worker] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2017-06-27 01:36:23.568 DEBUG 47446 --- [ Test worker] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2017-06-27 01:36:23.568 DEBUG 47446 --- [ Test worker] o.s.security.web.FilterChainProxy : /oauth/token reached end of additional filter chain; proceeding with original chain
2017-06-27 01:36:23.569 DEBUG 47446 --- [ Test worker] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /oauth/token
2017-06-27 01:36:23.569 DEBUG 47446 --- [ Test worker] .s.o.p.e.FrameworkEndpointHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException]
2017-06-27 01:36:23.572 DEBUG 47446 --- [ Test worker] .o.p.p.ResourceOwnerPasswordTokenGranter : Getting access token for: testclient
2017-06-27 01:36:23.572 DEBUG 47446 --- [ Test worker] o.s.s.authentication.ProviderManager : Authentication attempt using de.example.microservice.authservice.authentication.behavior.CustomAuthenticationProvider
2017-06-27 01:36:23.656 DEBUG 47446 --- [ Test worker] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2017-06-27 01:36:23.656 DEBUG 47446 --- [ Test worker] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
MockHttpServletRequest:
HTTP Method = POST
Request URI = /oauth/token
Parameters = {username=[testuser], password=[testpassword], grant_type=[password]}
Headers = {Authorization=[Basic dGVzdGNsaWVudDp0ZXN0Y2xpZW50c2VjcmV0]}
Handler:
Type = org.springframework.security.oauth2.provider.endpoint.TokenEndpoint
Method = public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOiJmZjgwODA4MTVjZTZjMzBkMDE1Y2U2YzM2MmYzMDAyNyIsInVzZXJfbmFtZSI6InRlc3R1c2VyIiwic2NvcGUiOlsicmVhZCIsIndpcnRlIl0sIm9yZ2FuaXNhdGlvbiI6ImRlZmF1bHQiLCJleHAiOjE0OTg1NjMzODMsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiJlZGRmZWUyZS01NTU2LTQ1YWItOTIwMC02NThiM2FkNmRiNWYiLCJjbGllbnRfaWQiOiJ0ZXN0Y2xpZW50In0.bL9mLo1Ao6oUBA3BxrIIEWTEXVlTml5GqeoeAKqA_pXDFBn-gIRafRH8ji3BceTg-cjih_-cYYAbRiVmjsCAUd0nE-chwIwhwPp2WSAfgz9OHd531VsDOX7l8-vkR_BUKY5X02pIf2W9ZlsqCZ-isarRzWI_AQpNgqwoIDcICDeuB1lNWqkwtwmI_f0cF3u0J2FuQBvye3Sj4xXmrQU0awCj0F891v6bPqkM0Wc5G6i8Mm-n-OnRbMqcckfxAsSqtDEYrDe3T6otFfREZ6AYTefMzQWYbYXDK0tCkohH46hNmKlbrXNWUrnwYLDeCZyOGm8bCrOihDzjYJgw5RshKQ","token_type":"bearer","expires_in":43199,"scope":"read wirte","accountId":"ff8080815ce6c30d015ce6c362f30027","organisation":"default","jti":"eddfee2e-5556-45ab-9200-658b3ad6db5f"}
Forwarded URL = null
Redirected URL = null
Cookies = []
2017-06-27 01:36:23.684 INFO 47446 --- [ Test worker] ilder$StaticRequestMappingHandlerMapping : Mapped "{[/api/me],methods=[GET],produces=[application/json;charset=UTF-8]}" onto public java.security.Principal de.example.microservice.authservice.rest.behavior.AccountDetailsController.user(java.security.Principal)
2017-06-27 01:36:23.692 INFO 47446 --- [ Test worker] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#734a6c74
2017-06-27 01:36:23.696 INFO 47446 --- [ Test worker] o.s.mock.web.MockServletContext : Initializing Spring FrameworkServlet ''
2017-06-27 01:36:23.696 INFO 47446 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2017-06-27 01:36:23.696 INFO 47446 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 0 ms
The TestException is
java.lang.IllegalArgumentException: json string can not be null or empty
at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:386)
at com.jayway.jsonpath.internal.JsonContext.parse(JsonContext.java:81)
at com.jayway.jsonpath.JsonPath.parse(JsonPath.java:596)
at de.example.microservice.authservice.verifier.tests.OauthserviceTest.validate_shouldReturnAccountDetails(OauthserviceTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method
I guess the autogenerated Test is not executed but didn't know how to debug them. The get Oauth2 token works perfect and also the execution of the oath() method in the verifier Class.
I ended up with the following test setup:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
#ContextConfiguration
#WebAppConfiguration
#ActiveProfiles("test")
public abstract class UserDetailsControllerTestBase {
public static Logger log = LoggerFactory.getLogger(UserDetailsControllerTestBase.class);
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
#Autowired
FilterChainProxy springSecurityFilterChain;
#Mock SecurityContext mockSecurityContext;
#Before
public void setUp() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
//RestAssured.baseURI="http://localhost";
//RestAssured.port = port;
mvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.defaultRequest(get("/api/me").with(user("user").roles("USER")))
.apply(springSecurity(springSecurityFilterChain))
.build();
RestAssuredMockMvc.mockMvc(mvc);
}
public String oauth(){
String token = "notValidToken";
try {
token = validAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
return "Bearer " + token;
}
public void assertIsNull(Object value){
assertThat(value, is(nullValue()));
}
private String validAccessToken() throws Exception {
String username = "user";
String password = "password";
MockHttpServletResponse response = mvc
.perform(post("/oauth/token")
.header("Authorization", "Basic "
+ new String(Base64Utils.encode(("client:clientsecret")
.getBytes())))
.param("username", username)
.param("password", password)
.param("grant_type", "password"))
.andDo(print())
.andReturn().getResponse();
return new ObjectMapper()
.readValue(response.getContentAsByteArray(), OAuthToken.class)
.accessToken;
}
#JsonIgnoreProperties(ignoreUnknown = true)
private static class OAuthToken {
#JsonProperty("access_token")
public String accessToken;
}
}
Check out the example Solution Repository for more details
Yes. Just run the plugin in EXPLICIT mode. That way you can configure restassured to shoot any URL and you'll be able to setup your base class however you want to. Example https://cloud.spring.io/spring-cloud-contract/reference/html/project-features.html#features-context-paths

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