Mocking a suspend function asks for an extra parameter - Mockito - java

I am trying to mock a suspend function which accepts 3 parameters, but when I try to mock it asks for 4 parameters
suspend fun notifyBandSuspend(serviceType: String, id: String, action: TimeAction): GenericResponse =
order.serviceOrderband(serviceType, id, action)
Mocking
when(repository.notifyBandSuspend(any(), any(), any())).thenReturn(new GenericResponse());
Error is - Expected 4 arguments but found 3
Imports
// Mockito
testImplementation "org.mockito:mockito-core:2.28.2"
androidTestImplementation "org.mockito:mockito-core:2.28.2"
androidTestImplementation "com.linkedin.dexmaker:dexmaker-mockito:2.28.0"
Any idea how to fix this please
EDIT
as it was complaining about 4th parameter
I passed 4 parameters like this
when(orderRepository.notifyBandSuspend(anyString(), anyString(), any(), any())).thenReturn(new GenericResponse());
that gives me an error:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 4 recorded:
Error
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 4 recorded:
-> at com.xxx.xx.test.scenarios.ServiceOrderViewScenario.setup(ServiceOrderViewScenario.java:46)
-> at com.xxx.xx.test.scenarios.ServiceOrderViewScenario.setup(ServiceOrderViewScenario.java:46)
-> at com.xxx.xx.test.scenarios.ServiceOrderViewScenario.setup(ServiceOrderViewScenario.java:46)
-> at com.xxx.xx.test.scenarios.ServiceOrderViewScenario.setup(ServiceOrderViewScenario.java:46)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at com.xxx.xx.clean.orderview.data.OrderRepository.notifyBandSuspend(OrderRepository.kt:22)
at com.xxx.xx.test.scenarios.ServiceOrderViewScenario.setup(ServiceOrderViewScenario.java:46)
at com.xxx.xx.test.BaseTest.scenario(BaseTest.java:79)
at com.xxx.xx.test.ServiceOrderViewTests.testAirStartOrder(ServiceOrderViewTests.java:45)
at java.lang.reflect.Method.invoke(Native Method)
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 androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
at androidx.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:527)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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 androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
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)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
at com.xxx.xx.test.runner.UnlockDeviceAndroidJUnitRunner.onStart(UnlockDeviceAndroidJUnitRunner.java:42)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145)
Thanks
Rao

Related

Assert that a specific exception is thrown in a Kafka listener method

I have a #KafkaListener method that might throw an IllegalArgumentException. For the sake of the question it might look like:
#KafkaListener(topics = "SomeTopic")
public void listen(ConsumerRecord<String, SomeDto> record) {
throw new IllegalArgumentException("Whats up?");
}
As part of integration testing (using Spring Boot and JUnit) I want to test the method and assert that an exception has indeed been thrown. In my test class, I have a test that boils down to:
#Rule
public ExpectedException exceptionRule = ExpectedException.none();
#Test
public void createHierarchy_invalidEventType_exception() {
exceptionRule.expect(IllegalArgumentException.class);
kafkaTemplate.send("SomeTopic", someDto);
}
The log shows:
org.springframework.kafka.listener.ListenerExecutionFailedException: Listener method 'public void com.something.EventService.listenPosition(org.apache.kafka.clients.consumer.ConsumerRecord)' threw exception; nested exception is java.lang.IllegalArgumentException: This event type is not supported.;
So IllegalArgumentException got wrapped into ListenerExecutionFailedException and I modified my test method:
#Test
public void createHierarchy_invalidEventType_exception() {
exceptionRule.expectCause(isA(IllegalArgumentException.class));
kafkaTemplate.send("SomeTopic", someDto);
}
But the log still shows the same stack trace. What am I doing wrong? How do I verify that the #KafkaListener method indeed threw the exception?
EDIT:
Here's the test's stack trace:
java.lang.AssertionError: Expected test to throw (an instance of org.springframework.kafka.listener.ListenerExecutionFailedException and exception with cause is an instance of java.lang.IllegalArgumentException)
at org.junit.Assert.fail(Assert.java:88)
at org.junit.rules.ExpectedException.failDueToMissingException(ExpectedException.java:263)
at org.junit.rules.ExpectedException.access$200(ExpectedException.java:106)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:245)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Thanks.

How to use Apache Beam DSL APIs?

I am trying to implement the DSL API example from the Apache Beam documentation. I am using the newest versions of the apache beam libraries (2.4.0)
The code I am running is the same as in the docs:
#Rule
public final transient TestPipeline p = TestPipeline.create();
#Test
public void dslTest() {
RowType appType = RowSqlType
.builder()
.withIntegerField("appId")
.withVarcharField("description")
.withTimestampField("rowtime")
.build();
// Create a concrete row with that type.
Row row = Row.withRowType(appType)
.addValues(1, "Some cool app", new Date())
.build();
// Create a source PCollection containing only that row
PCollection<Row> testApps = PBegin
.in(p)
.apply(Create
.of(row)
.withCoder(appType.getRowCoder()));
PCollection<Row> filteredNames = testApps.apply(
BeamSql.query(
"SELECT appId, description, rowtime "
+ "FROM PCOLLECTION "
+ "WHERE appId=1"));
}
This always fails with the following error:
java.lang.AssertionError
at org.apache.beam.sdks.java.extensions.sql.repackaged.org.apache.calcite.plan.volcano.VolcanoPlanner.changeTraits(VolcanoPlanner.java:546)
at org.apache.beam.sdks.java.extensions.sql.repackaged.org.apache.calcite.tools.Programs$RuleSetProgram.run(Programs.java:365)
at org.apache.beam.sdks.java.extensions.sql.repackaged.org.apache.calcite.prepare.PlannerImpl.transform(PlannerImpl.java:336)
at org.apache.beam.sdk.extensions.sql.impl.planner.BeamQueryPlanner.convertToBeamRel(BeamQueryPlanner.java:165)
at org.apache.beam.sdk.extensions.sql.impl.planner.BeamQueryPlanner.validateAndConvert(BeamQueryPlanner.java:156)
at org.apache.beam.sdk.extensions.sql.impl.planner.BeamQueryPlanner.convertToBeamRel(BeamQueryPlanner.java:144)
at org.apache.beam.sdk.extensions.sql.QueryTransform.expand(QueryTransform.java:73)
at org.apache.beam.sdk.extensions.sql.QueryTransform.expand(QueryTransform.java:47)
at org.apache.beam.sdk.Pipeline.applyInternal(Pipeline.java:537)
at org.apache.beam.sdk.Pipeline.applyTransform(Pipeline.java:472)
at org.apache.beam.sdk.values.PCollection.apply(PCollection.java:286)
at PipelineTest.dslTest(PipelineTest.java:42)
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.apache.beam.sdk.testing.TestPipeline$1.evaluate(TestPipeline.java:324)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
What is the correct way to run this test, or is this a bug and the dsl apis are not working?
It looks like a known issue, there's an assertion inside a planner which Beam fails to satisfy, see this jira. The fix for it is not ready at the moment.
Current workaround is to disable assertions, depending on your build system:
if you're using gradle, then in build.gradle you will have something like this:
test {
jvmArgs "-da"
}
if you're using maven, then in pom.xml you will have something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-da</argLine>

Spring Boot Integration test throws error "java.lang.IllegalStateException: Timeout on blocking read for 5000 MILLISECONDS"

The issue happens on my project that uses Spring webflux via Spring boot 2.0.0.M3. Below is the dependencies of project,
dependencies {
compile 'org.springframework.boot:spring-boot-starter-actuator',
'org.springframework.cloud:spring-cloud-starter-config',
'org.springframework.cloud:spring-cloud-sleuth-stream',
'org.springframework.cloud:spring-cloud-starter-sleuth',
'org.springframework.cloud:spring-cloud-starter-stream-rabbit',
'org.springframework.boot:spring-boot-starter-data-mongodb-reactive',
'org.springframework.boot:spring-boot-starter-data-redis-reactive',
'org.springframework.boot:spring-boot-starter-integration',
"org.springframework.integration:spring-integration-amqp",
"org.springframework.integration:spring-integration-mongodb",
'org.springframework.retry:spring-retry',
'org.springframework.boot:spring-boot-starter-webflux',
"org.springframework.boot:spring-boot-devtools",
'com.fasterxml.jackson.datatype:jackson-datatype-joda',
'joda-time:joda-time:2.9.9',
'org.javamoney:moneta:1.0',
'com.squareup.okhttp3:okhttp:3.8.1',
"net.logstash.logback:logstash-logback-encoder:4.11",
'org.apache.commons:commons-lang3:3.5'
compileOnly 'org.projectlombok:lombok:1.16.18'
testCompile 'org.springframework.boot:spring-boot-starter-test',
'io.projectreactor:reactor-test',
'org.apache.qpid:qpid-broker:6.1.2',
'de.flapdoodle.embed:de.flapdoodle.embed.mongo'
integTestCompile sourceSets.main.output
integTestCompile configurations.testCompile
integTestCompile sourceSets.test.output
integTestRuntime configurations.testRuntime
}
I have an REST API, and the code is below:
#RestController
#RequestMapping(value="/internal/note")
#Slf4j
public class NoteController {
#Autowired
NoteRepository noteRepository;
#GetMapping("/request/{id}")
public Mono<Note> getNoteByRequestid(#PathVariable("id") String requestid) {
logger.debug("Requesting note by request id '{}'.", requestid);
return noteRepository.findByRequestid(requestid).doOnSuccess(note ->
logger.debug("Found note '{}'.", note))
.doOnSuccess(response -> logger.debug("Successfully found note by request id '{}'.", requestid));
}
}
The code works fine. When calling the API using Postman, it returns the correct result.
I have the Integration test code like below:
final String data = "{xxxxx}";//JSON Data
final Note newNote = noteRepository.save(objectMapper.readValue(data, Note.class)).block(Duration.ofSeconds(3));
final String requestid = "5982C7366FF1C55D20CF2B70";
this.webClient.get().uri("/internal/note/request/{id}", requestid).accept(MediaType.APPLICATION_JSON_UTF8)
.exchange().expectStatus().isOk();
But the test fails throwing error message like below:
java.lang.IllegalStateException: Timeout on blocking read for 5000 MILLISECONDS
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:109)
at reactor.core.publisher.Mono.block(Mono.java:1304)
at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultRequestBodyUriSpec.toResponseSpec(DefaultWebTestClient.java:291)
at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultRequestBodyUriSpec.exchange(DefaultWebTestClient.java:269)
at cn.demo.handler.NoteHandlerTest.testGetNoteByRequestidWithPriceField(NoteHandlerTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
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)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Any advice on how to solve the issue?
This might be a bug in the Framework, but given the amount of stuff you've got on the classpath, you should try to create a minimal, sample project reproducing that and open an issue against Spring Framework (https://jira.spring.io).
The request timeout defaults to 5 seconds. Do your tests take longer than that to run? Maybe while you're actively using your computer simultaneously for other tasks and processes?
If so, when you configure your WebTestClient, set the responseTimeout() to something higher, like so:
#Autowired
private WebTestClient webTestClient;
#BeforeEach
public void setUp() {
webTestClient =
webTestClient
.mutate()
.responseTimeout(Duration.ofMillis(30000))
.build();
}

Contiperf2 not working with my existing JUnit test case

For performance testing, I am trying to use Contiperf http://databene.org/contiperf with my JUnit testcases
With independent test class contiperf is working.
but when I using Contiperf with my existing passing test case, its not working.
import org.databene.contiperf.junit.ContiPerfRule;
import org.databene.contiperf.junit.ContiPerfSuiteRunner;
import org.junit.Rule;
public class TU_XSL_OrderDlt extends TranslatorUtls {
#Rule
public ContiPerfRule i = new ContiPerfRule();
#Test
#PerfTest(invocations = 1, threads = 1)
public void testNormalTranslation() throws Exception {
assertTranslation("testdata/OrderDeltInput.xml", "testdata/OrderDltOutput.xml");
}
}
Following exception I get:
java.lang.RuntimeException: java.lang.NoSuchFieldException: fNext
at org.databene.contiperf.junit.ContiPerfRule.apply(ContiPerfRule.java:176)
at org.junit.runners.BlockJUnit4ClassRunner.withMethodRules(BlockJUnit4ClassRunner.java:365)
at org.junit.runners.BlockJUnit4ClassRunner.withRules(BlockJUnit4ClassRunner.java:355)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:278)
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:50)
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)
Caused by: java.lang.NoSuchFieldException: fNext
at java.lang.Class.getDeclaredField(Class.java:2070)
at org.databene.contiperf.junit.ContiPerfRule.apply(ContiPerfRule.java:166)
... 17 more
JUnit 4.12 applies that field renaming, the PR to fix it was sent a long time ago.
I suggest you use version 2.4.3 that has the change and is already on maven central.
Please note that the dependency group has changed, but other than changing the imports the code should remain the same.

PAX-CDI: inter bundle producer methods

With PAX-CDI: How can I define a producer method in one bundle and consume it in another bundle?
I guess since in PAX-CDI inter bundle bean injections has to use the OSGi service registry, the #OsgiServiceProvider annotation is also used for producer methods.
And since I want a different instance for each injection point, I guess I need the prototype scope.
So I tried (among other things):
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
#Produces
#OsgiServiceProvider
#PrototypeScoped
public Logger getLogger(InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass());
}
And on the consumer side I tried:
#Inject
#OsgiService
private Logger logger;
But it's not working.
I'm getting different exceptions depending on the execution environment.
Eg. with Pax Exam:
testParameterizedTypeSupported(org.ops4j.pax.cdi.test.InterBundleProducesTest) Time elapsed: 10.043 sec <<< ERROR!
org.ops4j.pax.swissbox.tracker.ServiceLookupException: gave up waiting for service org.slf4j.Logger
at org.ops4j.pax.swissbox.tracker.ServiceLookup.getService(ServiceLookup.java:199)
at org.ops4j.pax.swissbox.tracker.ServiceLookup.getService(ServiceLookup.java:136)
at org.ops4j.pax.exam.inject.internal.ServiceInjector.injectField(ServiceInjector.java:89)
at org.ops4j.pax.exam.inject.internal.ServiceInjector.injectDeclaredFields(ServiceInjector.java:69)
at org.ops4j.pax.exam.inject.internal.ServiceInjector.injectFields(ServiceInjector.java:61)
at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.createTest(ContainerTestRunner.java:61)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:68)
at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:37)
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)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.invokeViaJUnit(JUnitProbeInvoker.java:124)
at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.findAndInvoke(JUnitProbeInvoker.java:97)
at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.call(JUnitProbeInvoker.java:73)
at org.ops4j.pax.exam.nat.internal.NativeTestContainer.call(NativeTestContainer.java:109)
at org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactor.invoke(EagerSingleStagedReactor.java:109)
at org.ops4j.pax.exam.junit.impl.ProbeRunner$2.evaluate(ProbeRunner.java:267)
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.ops4j.pax.exam.junit.impl.ProbeRunner.run(ProbeRunner.java:98)
at org.ops4j.pax.exam.junit.PaxExam.run(PaxExam.java:93)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
And in my project environment I'm getting even if I don't have a consumer:
ERROR: org.ops4j.pax.cdi.extender (41): [CdiExtender(33)] The activate method has thrown an exception
org.ops4j.lang.Ops4jException: org.jboss.weld.exceptions.DefinitionException: WELD-001406: Cannot inject [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedMethod] #Produces #OsgiServiceProvider #PrototypeScoped public somepackage.SomeClass.getLogger(InjectionPoint) in a non #Dependent scoped bean
at org.ops4j.pax.cdi.weld.impl.WeldCdiContainer.doStart(WeldCdiContainer.java:99)
at org.ops4j.pax.cdi.spi.AbstractCdiContainer.start(AbstractCdiContainer.java:89)
at org.ops4j.pax.cdi.extender.impl.CdiExtender.createContainer(CdiExtender.java:132)
at org.ops4j.pax.cdi.extender.impl.CdiExtender.addingBundle(CdiExtender.java:86)
at org.ops4j.pax.cdi.extender.impl.CdiExtender.addingBundle(CdiExtender.java:44)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerAdding(BundleTracker.java:469)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerAdding(BundleTracker.java:415)
at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
at org.osgi.util.tracker.AbstractTracked.trackInitial(AbstractTracked.java:183)
at org.osgi.util.tracker.BundleTracker.open(BundleTracker.java:156)
at org.ops4j.pax.cdi.extender.impl.CdiExtender.activate(CdiExtender.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:231)
at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:39)
at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:624)
at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:508)
at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:149)
at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:315)
at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:127)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:871)
at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:838)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:850)
at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:931)
at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:895)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1480)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1401)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.trackAdding(ServiceTracker.java:1210)
at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.track(ServiceTracker.java:1148)
at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:1432)
at org.apache.felix.framework.util.EventDispatcher.invokeServiceListenerCallback(EventDispatcher.java:987)
at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:838)
at org.apache.felix.framework.util.EventDispatcher.fireServiceEvent(EventDispatcher.java:545)
at org.apache.felix.framework.Felix.fireServiceEvent(Felix.java:4547)
at org.apache.felix.framework.Felix.registerService(Felix.java:3521)
at org.apache.felix.framework.BundleContextImpl.registerService(BundleContextImpl.java:350)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentManager.java:1003)
at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentManager.java:992)
at org.apache.felix.scr.impl.manager.RegistrationManager.changeRegistration(RegistrationManager.java:134)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.registerService(AbstractComponentManager.java:1044)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:841)
at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:419)
at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.enableComponents(ConfigurableComponentHolder.java:376)
at org.apache.felix.scr.impl.BundleComponentActivator.initialize(BundleComponentActivator.java:172)
at org.apache.felix.scr.impl.BundleComponentActivator.<init>(BundleComponentActivator.java:120)
at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:258)
at org.apache.felix.scr.impl.Activator.access$000(Activator.java:45)
at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:185)
at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)
at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:479)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:414)
at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)
at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:443)
at org.apache.felix.framework.util.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:913)
at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:834)
at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:516)
at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4531)
at org.apache.felix.framework.Felix.startBundle(Felix.java:2169)
at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1368)
at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:308)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.jboss.weld.exceptions.DefinitionException: WELD-001406: Cannot inject [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedMethod] #Produces #OsgiServiceProvider #PrototypeScoped public somepackage.SomeClass.getLogger(InjectionPoint) in a non #Dependent scoped bean
at org.jboss.weld.bootstrap.Validator.validateMetadataInjectionPoint(Validator.java:327)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:279)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:155)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:518)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
... 1 more
ERROR: org.ops4j.pax.cdi.extender (41): [CdiExtender(33)] Failed creating the component instance; see log for reason
As far as I can tell it is not possible to use #Produces over bundle boundaries.
You can offer and inject an OSGi service of course but it will not work for your case. You want the Logger to be created for each bean and have a different logger name that depends on the bean class. This is not possible with OSGi services. You create a service once and inject it.
For logging the whole effort you do is not really necessary. Just use the slf4j factory as outside OSGi. It should work fine.

Categories