In a test I want to verify that a model would call a client when a method of this model is called.
The class under test - the model class - is an object singleton. (KubernetesResourceModel.kt)
object KubernetesResourceModel {
…
private fun createClient(): NamespacedKubernetesClient {
return DefaultKubernetesClient(ConfigBuilder().build())
}
The actual call to the client - DefaultKubernetesClient - happens in an instance variable within KubernetesResourceModel (Cluster.kt)
class Cluster(val client: NamespacedKubernetesClient) {
...
private fun loadAllNameSpaces(): Sequence<Namespace> {
return client.namespaces().list().items.asSequence()
}
In my test I stub the client and then verify that a call to the client library is executed when KubernetesResourceModel.getAllNamespaces is called, (KubernetesResourceModelTest.kt):
#Test
fun `should call list namespaces on client`() {
// given
mockClient(emptyList())
// when
KubernetesResourceModel.getAllNamespaces()
// then
verify { anyConstructed<DefaultKubernetesClient>().namespaces().list().items }
}
...
private fun mockClient(namespaces: List<Namespace>) {
// client.namespaces().list().items.asSequence()
mockkConstructor(DefaultKubernetesClient::class)
every { anyConstructed<DefaultKubernetesClient>().namespaces() } returns
spyk {
every { list() } returns
spyk {
every { items } returns
namespaces
}
every { watch(any()) } returns
mockk()
}
The mocking works and I see KubernetesResourceModel.getAllNamespaces() returning the empty list that I passed along when mocking (mockClient(emptyList())).
Unfortunately the verification
verify { anyConstructed<DefaultKubernetesClient>().namespaces().list().items } (KubernetesResourceModelTest.kt)
fails telling me that no call on client.namespaces().list() happened:
Verification failed: call 2 of 3: NonNamespaceOperation(child of mockkConstructor<DefaultKubernetesClient>()#1).list()) was not called
java.lang.AssertionError: Verification failed: call 2 of 3: NonNamespaceOperation(child of mockkConstructor<DefaultKubernetesClient>()#1).list()) was not called
at io.mockk.impl.recording.states.VerifyingState.failIfNotPassed(VerifyingState.kt:66)
at io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:42)
at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
at io.mockk.impl.eval.VerifyBlockEvaluator.verify(VerifyBlockEvaluator.kt:30)
at io.mockk.MockKDsl.internalVerify(API.kt:118)
at io.mockk.MockKKt.verify(MockK.kt:139)
at io.mockk.MockKKt.verify$default(MockK.kt:136)
at org.jboss.tools.intellij.kubernetes.model.KubernetesResourceModelTest.should call list namespaces on client(KubernetesResourceModelTest.kt:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch
Any idea what I am missing?
Related
When using Mockito in JUnit4, I encounter the error in the title.
My code is shown below
package cn.patest.judgerAutoscalerKotlin
import org.junit.Test
import org.mockito.*
import java.lang.RuntimeException
class CalculateScaleToTest {
#Mock
private lateinit var test: cn.patest.judgerAutoscalerKotlin.Test
private fun mockTest() {
test = cn.patest.judgerAutoscalerKotlin.Test()
Mockito.doAnswer { 1 }.`when`(test).test()
}
#Test
fun z() {
mockTest()
}
}
package cn.patest.judgerAutoscalerKotlin
class Test() {
fun test(): Int {
return 1
}
}
Error details are shown below:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();
at cn.patest.judgerAutoscalerKotlin.CalculateScaleToTest.mockTest(CalculateScaleToTest.kt:53)
at cn.patest.judgerAutoscalerKotlin.CalculateScaleToTest.z(CalculateScaleToTest.kt:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
I searched with google and found some similar issues but they have different situations from mine.
With:
test = cn.patest.judgerAutoscalerKotlin.Test()
you create a real object, not a mocked one.
Remove the above line and add:
#Before
fun before() {
MockitoAnnotations.initMocks( this )
}
Reference:
Mock
MockitoAnnotations
MockitoAnnotations.initMocks(this) method has to be called to initialize annotated fields.
Note also that mocking the class under test in a real environment doesn't make any sense (in contrast to a MCVE like here).
In some tests with a securityCheckDefinition called "aov", i tried to store some user info in it's attributes:
protected AuthenticatedUser createUser() {
Map<String,Object> attributes = new HashMap<>();
attributes.put("user", new UserOutput(....)); //store user info for later use
return new AuthenticatedUser(displayName, displayName, this.getName(), attributes);
}
But now when doing the preauthorize from a Cordova App, it fails when doing a deserialization of the persisted user data:
POST /mfp/api/preauth/v1/preauthorize
{"client_id":"c9db821c-87d8-4949-9c9a-152a832a771e","scope":"aov","challengeResponse":{"aov":{"username":"12345","password":"12345"}}}
{"errorCode":"UNEXPECTED_ERROR","errorMsg":"Unexpected error encountered"}
UserOutput object:
public class UserOutput {
private String token;
public UserOutput() {
}
public UserOutput(String token, boolean k, boolean k2, boolean k3) {
this(token); // TODO
}
public UserOutput(String token) {
super();
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
Server error
[12/08/16 12:01:19:906 CEST] 0000009f com.ibm.mfp.server.registration.internal.ClientRegistryDao E Failed to read client c9db821c-87d8-4949-9c9a-152a832a771e
com.fasterxml.jackson.databind.JsonMappingException: Invalid type id 'com.test.app.api.model.io.user.UserOutput' (for id type 'Id.class'): no such class found (through reference chain: com.ibm.mfp.server.registration.internal.PersistedClientData["associatedUsers"]->java.util.HashMap["aov"]->com.ibm.mfp.server.registration.external.model.AuthenticatedUser["attributes"]->java.util.HashMap["user"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177)
at com.fasterxml.jackson.databind.deser.std.ContainerDeserializerBase.wrapAndThrow(ContainerDeserializerBase.java:88)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:497)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:342)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:110)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromObject(AsArrayTypeDeserializer.java:58)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserializeWithType(MapDeserializer.java:376)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:521)
at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:101)
at com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap.findDeserializeAndSet(BeanPropertyMap.java:285)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:248)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:136)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:485)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:342)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:110)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromObject(AsArrayTypeDeserializer.java:58)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserializeWithType(MapDeserializer.java:376)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:521)
at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:101)
at com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap.findDeserializeAndSet(BeanPropertyMap.java:285)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:248)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:136)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3564)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2580)
at com.ibm.mfp.server.registration.internal.ClientRegistryDao.toClientData(ClientRegistryDao.java:154)
at com.ibm.mfp.server.registration.internal.ClientRegistryDao.get(ClientRegistryDao.java:51)
at com.ibm.mfp.server.registration.internal.RegistrationServiceImpl.getCached(RegistrationServiceImpl.java:333)
at com.ibm.mfp.server.registration.internal.RegistrationServiceImpl.getClientData(RegistrationServiceImpl.java:188)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy176.getClientData(Unknown Source)
at com.ibm.mfp.server.security.internal.context.ClientSecurityContextImpl.load(ClientSecurityContextImpl.java:166)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy180.load(Unknown Source)
at com.ibm.mfp.server.security.internal.services.PreAuthorizationServiceImpl.authorize(PreAuthorizationServiceImpl.java:33)
at com.ibm.mfp.server.security.internal.rest.PreAuthorizationEndpoint$1.call(PreAuthorizationEndpoint.java:80)
at com.ibm.mfp.server.security.internal.rest.PreAuthorizationEndpoint$1.call(PreAuthorizationEndpoint.java:77)
at com.ibm.mfp.server.persistency.internal.transaction.StorageManagerImpl.doWithStorage(StorageManagerImpl.java:49)
at com.ibm.mfp.server.security.internal.rest.PreAuthorizationEndpoint.authorize(PreAuthorizationEndpoint.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1287)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:475)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1158)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:4867)
at com.ibm.ws.webcontainer31.osgi.webapp.WebApp31.handleRequest(WebApp31.java:523)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.handleRequest(DynamicVirtualHost.java:297)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:997)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:262)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:955)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:341)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:470)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:404)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:284)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:255)
at com.ibm.ws.tcpchannel.internal.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:174)
at com.ibm.ws.tcpchannel.internal.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:83)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:504)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:574)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:929)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1018)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Invalid type id 'com.test.app.api.model.io.user.UserOutput' (for id type 'Id.class'): no such class found
at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver._typeFromId(ClassNameIdResolver.java:66)
at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver.typeFromId(ClassNameIdResolver.java:48)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:157)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:94)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromAny(AsArrayTypeDeserializer.java:68)
at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserializeWithType(UntypedObjectDeserializer.java:500)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:487)
... 98 more
I've tried to remove the adapter, change the securityCheckDefinition name, etc. but it continues to remember the stored data in the old securityCheckDefinition 'aov' and always fails.
I have 2 questions:
How can i remove this user data to avoid the excepcion?
If the object UserOutput hasn't change and is still in the classpath, why it's failing jackson?
Thanks
Sergio
As mentioned by Nathan, this may be a product defect. Please open a PMR to have the development team further investigate it.
As a workaround:
The error is that it does not let you use a custom class in the attributes map. In the meantime I suggest you use standard Java classes to store your data (maps, etc).
I am trying to use HikariCP with h2 database. Here is my class responsible for sql
#Singleton
#Log
class SqlPersistence {
def config
{
def props = new Properties()
new File("build/resources/main/db.properties").withInputStream {
props.load(it)
}
log.info "Loaded properties: $props"
config = new HikariConfig(props)
}
#Lazy def ds = new HikariDataSource(config)
#Lazy def sql = new Sql(ds)
}
But when I try to run it using gradle task I get this error
Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: 'org.h2.jdbcx.JdbcDataSource'
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:89)
at com.zaxxer.hikari.pool.PoolBase.initializeDataSource(PoolBase.java:293)
at com.zaxxer.hikari.pool.PoolBase.<init>(PoolBase.java:90)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:101)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:71)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorS
ite.java:102)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:232)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:244)
at repository.persistence.SqlPersistence.getDs(SqlPersistence.groovy:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at org.codehaus.groovy.runtime.metaclass.MethodMetaProperty$GetBeanMethodMetaProperty.getProperty(MethodMetaProperty
.java:73)
at org.codehaus.groovy.runtime.callsite.GetEffectivePogoPropertySite.getProperty(GtivePogoPropertySite.java:82)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:304)
at repository.persistence.SqlPersistence.getSql(SqlPersistence.groovy:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at org.codehaus.groovy.runtime.metaclass.MethodMetaProperty$GetBeanMethodMetaProperty.getProperty(MethodMetaProperty
.java:73)
at org.codehaus.groovy.runtime.callsite.GetEffectivePogoPropertySite.getProperty(GetEffectivePogoPropertySite.java:8
2)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:304)
at repository.persistence.SqlPersistence.selectAll(SqlPersistence.groovy:42)
at repository.persistence.SqlPersistence$selectAll.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
at repository.BookRepository.findAll(BookRepository.groovy:11)
at repository.BookRepository$findAll.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:114)
at service.BookService.findAll(BookService.groovy:13)
at service.BookService$findAll.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:114)
at script.run(script.groovy:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:914)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:897)
at org.codehaus.groovy.runtime.InvokerHelper.runScript(InvokerHelper.java:407)
at org.codehaus.groovy.runtime.InvokerHelper$runScript.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:130)
at script.main(script.groovy)
Caused by: java.lang.ClassNotFoundException: 'org.h2.jdbcx.JdbcDataSource'
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:76)
... 65 more
My build.gradle looks like this
apply plugin: 'groovy'
repositories {
jcenter()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.3'
compile 'com.h2database:h2:1.4.191'
compile 'com.zaxxer:HikariCP:2.4.5'
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
testCompile 'junit:junit:4.12'
testCompile 'cglib:cglib:3.2.1'
}
task runScript(dependsOn: 'compileJava', type: JavaExec) {
main = 'script'
classpath = sourceSets.main.runtimeClasspath + sourceSets.main.output
}
Why it's unable to find driver?
P.S. there is always some issue with using sql drivers...
It looks like your script is Java, but the snippet you posted is Groovy. So I think this is either an issue of how you call the Groovy part so that the H2 lib is not in Groovy classpath, because if I transform your code to Java and put it in script.java it works fine with your build.gradle. But it could also be a Groovy class loading problem. When I tried to access a database from a Gradle script (which essentially is also a Groovy script I had to do the following to get it working correctly:
// load JDBC drivers to the Groovy class loader to overcome java.sql.DriverManager quirks
Sql.classLoader.addURL new File('driver.jar').toURI().toURL()
Sql.withInstance('my:connection:string', 'user', 'pass', 'my.jdbc.DriverClass') {
it.execute 'select * from foo'
}
Maybe you need something similar.
I want to delete service include in serviceGroup of load balancer
but it make error !!
How to delete service & serviceGroup using java API?
VirtualIpAddress.Service vipService = VirtualIpAddress.service(client, virtualIpAddressId);
vipService.clearMask();
StringBuffer maskBuffer = new StringBuffer();
maskBuffer.append("mask");
maskBuffer.append("[");
maskBuffer.append("applicationDeliveryController");
maskBuffer.append(",billingItem");
maskBuffer.append(",ipAddress");
maskBuffer.append(",loadBalancerHardware[datacenterName,location]");
maskBuffer.append(",secureTransportCiphers");
maskBuffer.append(",secureTransportProtocols");
maskBuffer.append(",virtualServers[");
maskBuffer.append(" serviceGroups[");
maskBuffer.append(" routingMethod,routingType,serviceReferences,services[");
maskBuffer.append(" groupReferences,healthChecks,ipAddress]]]");
maskBuffer.append("]");
vipService.setMask(maskBuffer.toString());
VirtualIpAddress virtualIpAddress = vipService.getObject();
List<VirtualServer> virtualServerList = virtualIpAddress.getVirtualServers();
for(VirtualServer virtualServer : virtualServerList) {
List<Group> serviceGroupList = virtualServer.getServiceGroups();
for(Group group : serviceGroupList) {
List<com.softlayer.api.service.network.application.delivery.controller.loadbalancer.LoadBalancerService> serviceList = group.getServices();
for(com.softlayer.api.service.network.application.delivery.controller.loadbalancer.LoadBalancerService service : serviceList) {
LoadBalancerService.Service loadBalancerService = LoadBalancerService.service(client, service.getId());
System.out.println("loadBalancerService : " + loadBalancerService);
serviceDelFlag = loadBalancerService.deleteObject();
}
}
}
occurring error:
serviceGroupService : Service: SoftLayer_Network_Application_Delivery_Controller_LoadBalancer_VirtualServer with ID 234553
com.softlayer.api.ApiException$NotFound: Unable to find object with id of '234553'.(code: SoftLayer_Exception_ObjectNotFound, status: 404)
at com.softlayer.api.ApiException.fromError(ApiException.java:14)
at com.softlayer.api.RestApiClient$ServiceProxy.logAndHandleResponse(RestApiClient.java:308)
at com.softlayer.api.RestApiClient$ServiceProxy.invokeService(RestApiClient.java:359)
at com.softlayer.api.RestApiClient$ServiceProxy.invoke(RestApiClient.java:537)
at com.sun.proxy.$Proxy15.deleteObject(Unknown Source)
at com.ibm.softlayer.network.LoadBalancingTest_v1.getLoadBalancerDetail(LoadBalancingTest_v1.java:219)
at com.ibm.softlayer.network.LoadBalancingTest_v1.viewLoadBalancerList(LoadBalancingTest_v1.java:134)
at com.ibm.softlayer.network.LoadBalancingTest_v1.getLoadBalancers(LoadBalancingTest_v1.java:125)
at com.ibm.softlayer.network.LoadBalancingTest_v1.test(LoadBalancingTest_v1.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.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:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Well the ID 234553 does not exist for the object type SoftLayer_Network_Application_Delivery_Controller_LoadBalancer_VirtualServer, that is the error.
to get the valid IDs for the object you can call the method: http://sldn.softlayer.com/reference/services/SoftLayer_Account/getAdcLoadBalancers + an object mask to list the virtual server. here an example using Restful:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Account/getAdcLoadBalancers?objectMask=mask[virtualServers]
with this method you will delete service groups
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Application_Delivery_Controller_LoadBalancer_VirtualServer/dele
with this method you will delete services:
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Application_Delivery_Controller_LoadBalancer_Service/deleteObje
Just make sure you are using the correct IDs in the methods.
If you are still having issues with the Java client let me know to write an example in java for you.
Regards
So I'm trying to write my first gwt test. I got this part figured out that I need to add gwt-dev.jar to maven pom file, but now when I run my test I get this error:
testSimple(com.karq.tvkava.client.TelekanalServiceImplTest) Time elapsed: 3.809 sec <<< ERROR!
com.google.gwt.core.ext.UnableToCompleteException: (see previous log entries)
at com.google.gwt.dev.cfg.ModuleDef.checkForSeedTypes(ModuleDef.java:518)
at com.google.gwt.dev.cfg.ModuleDef.getCompilationState(ModuleDef.java:327)
at com.google.gwt.junit.JUnitShell.runTestImpl(JUnitShell.java:1342)
at com.google.gwt.junit.JUnitShell.runTestImpl(JUnitShell.java:1309)
at com.google.gwt.junit.JUnitShell.runTest(JUnitShell.java:650)
at com.google.gwt.junit.client.GWTTestCase.runTest(GWTTestCase.java:441)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at com.google.gwt.junit.client.GWTTestCase.run(GWTTestCase.java:296)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127)
at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345)
at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009)
And here's my test file
public class TelekanalServiceImplTest extends GWTTestCase {
#Override
public String getModuleName() {
return "com.karq.tvkava.tvkavaJUnit";
}
public void testSimple(){
boolean isSaved = true;
assertTrue(isSaved);
}
}
did you include
<inherits name="com.google.gwt.junit.JUnit" />
in your *.gwt.xml file?
If this doesn't fix your error you might want to take a look at Unit Testing GWT Applications with JUnit.