WireMock and Feign problem (Unit tests, Spring) - java

I'm trying to write some unit tests for few funcionts, which used feign to get information from another service. I try to use WireMock to do it but unfortunetely i get an exception like this :
feign.RetryableException: unexpected end of stream on http://localhost:8088/... executing POST http://localhost:8088/api
at feign.FeignException.errorExecuting(FeignException.java:249)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:129)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:89)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:100)
at com.sun.proxy.$Proxy94.info(Unknown Source)
at nbs.mobile.cashdesk.be.adapters.XXX.service.XXXAdapter
at nbs.mobile.cashdesk.be.application.service.XXX
at nbs.mobile.cashdesk.be.adapters.web.device.DeviceControllerTest.exampleTest(DeviceControllerTest.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at com.github.tomakehurst.wiremock.junit.WireMockClassRule$1.evaluate(WireMockClassRule.java:60)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at com.github.tomakehurst.wiremock.junit.WireMockClassRule$1.evaluate(WireMockClassRule.java:75)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.io.IOException: unexpected end of stream on http://localhost:8088/...
at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.java:236)
at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.java:115)
at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:94)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:43)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
at okhttp3.RealCall.execute(RealCall.java:81)
at feign.okhttp.OkHttpClient.execute(OkHttpClient.java:169)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:119)
... 40 more
Caused by: java.io.EOFException: \n not found: limit=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:240)
at okhttp3.internal.http1.Http1ExchangeCodec.readHeaderLine(Http1ExchangeCodec.java:242)
at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.java:213)
... 58 more
TestFunciton:
#Slf4j
#RunWith(SpringRunner.class)
#SpringBootTest
#TestPropertySource(
locations = "classpath:application-test.properties")
#AutoConfigureMockMvc
public class XXXTest {
#ClassRule
public static WireMockClassRule wireMockRule = new WireMockClassRule(8087, 8088);
#Rule
public WireMockClassRule instanceRule = wireMockRule;
#Autowired
private XXXClass xxxClass;
#BeforeEach
void setUp() {
WireMock.reset();
}
#AfterEach
void tearDown() {
}
#Test
public void exampleTest() {
wireMockRule.stubFor(WireMock.post(WireMock.urlEqualTo("/api"))
.willReturn(WireMock.aResponse().withHeader("Content-Type", "application/json")
.withStatus(200).withBody("{\"token\":\"1234\"}/n")))
;
log.error("Server Start");
log.error(wireMockRule.toString());
log.error(wireMockRule.getStubMappings().toString());
xxxClass.xxx("3214"); // This function is tested
assertEquals("12", "12");
}
}
I think that this information is enaugh to know something about this problem (I could add that it works fine with real services so in my opinion problem is somewhere in MockServer configuration).

I think you forgot to close your resulting json
.withStatus(200).withBody("{\"token\":\"1234\"/n")))
should be
.withStatus(200).withBody("{\"token\":\"1234\"}/n")))

The solution was to change port of mock server.

Related

How can I test IntegrationFlow with Jms.messageDrivenChannelAdapter

I tried to test IntegrationFlow which receives JMS message, then do some logic, send it to another JMS queue and then save it to the file.
I have such flow:
public class ProcessingFlow {
#Bean
public IntegrationFlow jmsProcessingFlow(
ActiveMQConnectionFactory activeMQConnectionFactory,
ValidationService validationService,
ConverterService converterService,
JmsMessageSender jmsMessageSender,
#Value("${folder.location}") String folderLocation) {
return IntegrationFlows.from(Jms.messageDrivenChannelAdapter(activeMQConnectionFactory).destination("JMSQueueFrom").id("jmsProcessing"))
.<String>handle((incomeFilePayload, messageHeaders) -> {
validationService.validate(incomeFilePayload);
String message = converterService.convert(incomeFilePayload);
jmsMessageSender.sendMessage("JMSQueueTo", message);
return incomeFilePayload;
})
.handle(Files.outboundAdapter(new File(folderLocation))
.fileNameGenerator("file.xml"))
.get();
}
}
I wrote such integration test:
#RunWith(SpringRunner.class)
#SpringIntegrationTest
#SpringBootTest(classes = {ProcessingFlowIntegrationTest.TestConfig.class})
#ActiveProfiles("test")
#DirtiesContext
public class ProcessingFlowIntegrationTest {
#MockBean
private ValidationService validationService;
#SpyBean
private ConverterService converterService;
#Autowired
private MockIntegrationContext mockIntegrationContext;
#After
public void tearDown() {
this.mockIntegrationContext.resetBeans();
}
#Test
public void shouldTestProcessingFlow() throws Exception {
TextMessage message = mock(TextMessage.class);
when(message.getText()).thenReturn(XmlContentEnum.CONTENT.getContent());
this.mockIntegrationContext.substituteMessageSourceFor("jmsProcessing", MockIntegration.mockMessageSource(message));
verify(validationService).validate(eq(message.getText()));
verify(converterService).convert(eq(message.getText()));
}
#TestConfiguration
#Import(value = {
ProcessingFlow.class,
JmsConfiguration.class,
TestConfig.class
})
static class TestConfig {
}
}
But after running I received such exception:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'jmsProcessing' is expected to be of type 'org.springframework.integration.endpoint.SourcePollingChannelAdapter' but was actually of type 'org.springframework.integration.jms.JmsMessageDrivenEndpoint'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:399)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:215)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:157)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:142)
at com.postpunk.flows.integration.ProcessingFlowIntegrationTest.shouldTestProcessingFlow(ProcessingFlowIntegrationTest.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
As I understood from exception my bean has type "org.springframework.integration.jms.JmsMessageDrivenEndpoint", but mockIntegrationContext expected "org.springframework.integration.endpoint.SourcePollingChannelAdapter". Does anybody know how can I test JmsMessageDrivenEndpoint correctly and what I did wrong?
Set noAutoStartup for the message-driven endpoint on the #SpringIntegrationTest.
Autowire the IntegrationFlow.
Then flow.getInputChannel().send(...);

Android kotlin Unit test case..?

How to write the test-cases for the below function.
public void trackMaxInterval(int trackingFastestInterval) {
if (trackingFastestInterval != 0) {
preferencesManager.writeLong(Constants.INTERVAL, interval);
} else {
preferencesManager.writeLong(Constants.INTERVAL, Service.INTERVAL);
}
}
I tried like below code but getting a null point exception it saying PreferencesManager is null
#Test
fun shouldSaveTracking_MaxIntervalValue() {
val preManager: PreferencesManager = mock(PreferencesManager::class.java)
loginPresenter.trackMaxInterval(2)
verify(preManager, times(1)).writeLong(Constants.INTERVAL, 2)
}
Attached error log.
java.lang.NullPointerException
at com.track.ui.login.LoginPresenter.trackMaxInterval(LoginPresenter.java:1055)
at com.track.ui.LoginPresenterTest.shouldSaveTracking_MaxIntervalValue(LoginPresenterTest.kt:142)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.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$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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)
It looks like your loginPresenter object does not hold a reference to a PreferencesManager instance. Even if you mock your PreferenceMananger in your test, you have to pass it somehow to the loginPresenter object.

How to write a Mockito test for Java 8 Predicate

I am using Spring Boot REST and Mockito. How can I write a test case?
Error:
java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
at java.util.concurrent.ConcurrentHashMap$KeySetView.add(ConcurrentHashMap.java:4595)
at com.mastercard.customer.data.management.refdata.service.RegionService.lambda$2(RegionService.java:58)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:419)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.mastercard.customer.data.management.refdata.service.RegionService.findAllRegions(RegionService.java:49)
at com.mastercard.customer.data.management.refdata.service.RegionServiceTest.findAllRegions_SuccessTest(RegionServiceTest.java:68)
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.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Code
public List<Employee> findAllEmployees() {
List<Object> obj = mongoTemplate.query(Department.class).distinct("employees").all();
List<Employee> employees = null;
if (!CollectionUtils.isEmpty(obj)) {
employees = obj.stream().map(e -> (Employee) e).filter(distinctByKey(Employee::getEmployeeCd)).collect(Collectors.toList());
}
return employees;
}
public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
Test case
#Test
public void findEmp() {
when(mongoTemplate.query(Department.class)).thenReturn(executableDepartment);
when(mongoTemplate.query(Department.class).distinct("employees")).thenReturn(distinctDepartment);
when(mongoTemplate.query(Department.class).distinct("employees").all()).thenReturn(obj);
when(obj.stream()).thenReturn(Stream.of(obj));
when(obj.stream().map(e -> (Region) e).thenReturn(Stream.of(region));
assertNotNull(empService.findAllRegions());
}
1) Try to set up you mocking one by one instead of cascading the calls:
when(mongoTemplate.query(Department.class)).thenReturn(executableDepartment);
when(executableDepartment).distinct("employees")).thenReturn(distinctDepartment);
when(distinctDepartment.all()).thenReturn(obj);
The executableDepartment and distinctDepartment need to be mocks as well of course.
2) Do not mock the List interface. Feed it with pre-configured data and allow the SUT to work on it as it is. Sp mocking should only be used in this part:
mongoTemplate.query(Department.class).distinct("employees").all();
So the part that provides data. But leave the actual logic to run as it is.

Assertj-swagger throws org.assertj.core.error.AssertJMultipleFailuresError Multiple Failures when executing test

I have a spring boot api application and I used springfox to generate swaggerv2 api documentation and I created a test to see if my api definitions are correct.
Heres how my configuration looks like:
#Configuration
#EnableSwagger2
public class SpringFoxConfig {
#Value("${my.app.version}")
private String appVersion;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).groupName("My App").select()
.apis(RequestHandlerSelectors.basePackage("my.com.app.controller"))
.paths(regex("/api/MyAppName.*")).build()
.globalOperationParameters(
Arrays.asList(new ParameterBuilder().name("UserKey").description("Unique user key.")
.modelRef(new ModelRef("string")).parameterType("header").required(true).build()))
.apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("My App API Documentaion")
.description("This documentation is for the MyApp.").version(appVersion)
.license("MyApp.cc").licenseUrl("https://myapp.com/").build();
}
private ApiKey apiKey() {
return new ApiKey("apiKey", "APIKEY", "header");
}
}
Here's how my test looks:
#Test
public void shouldFindNoDifferences() {
File implFirstSwaggerLocation = new File(
MyTest.class.getResource("/swagger.json").getFile());
File designFirstSwaggerLocation = new File(
MyTest.class.getResource("/swagger.yaml").getFile());
SwaggerAssertions.assertThat(implFirstSwaggerLocation.getAbsolutePath())
.isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
It's exactly what they have from their examples. When I run my test It throws this exception below:
Stack trace:
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (1 failure)
-- failure 1 --
[Checking Paths]
Expecting:
<["/api/myAppName",
"/api/myAppName/eventTypes",
"/api/myAppName/initialize",
"/api/myAppName/latest/{type}/{user}",
"/api/myAppName/stats/due/{ids}/custom/{days}",
"/api/myAppName/stats/due/{ids}/{period}",
"/api/myAppName/stats/orgs/most/{ids}/{period}",
"/api/myAppName/stats/orgs/{id}/{period}",
"/api/myAppName/stats/{ids}/{period}",
"/api/myAppName/stats/{ids}/{period}/{days}",
"/api/myAppName/summarize",
"/api/myAppName/{id}",
"/api/myAppName/{source}/events",
"/api/myAppName/{source}/events/batch"]>
to contain only:
<["/v2/api/myAppName/stats/orgs/{id}/{period}",
"/v2/api/myAppName/{source}/events/batch",
"/v2/api/myAppName/initialize",
"/v2/api/myAppName/eventTypes",
"/v2/api/myAppName/stats/due/{ids}/{period}",
"/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
"/v2/api/myAppName/{source}/events",
"/v2/api/myAppName/{id}",
"/v2/api/myAppName/latest/{type}/{user}",
"/v2/api/myAppName/stats/due/{ids}/custom/{days}",
"/v2/api/myAppName/stats/{ids}/{period}",
"/v2/api/myAppName",
"/v2/api/myAppName/summarize",
"/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
elements not found:
<["/v2/api/myAppName/stats/orgs/{id}/{period}",
"/v2/api/myAppName/{source}/events/batch",
"/v2/api/myAppName/initialize",
"/v2/api/myAppName/eventTypes",
"/v2/api/myAppName/stats/due/{ids}/{period}",
"/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
"/v2/api/myAppName/{source}/events",
"/v2/api/myAppName/{id}",
"/v2/api/myAppName/latest/{type}/{user}",
"/v2/api/myAppName/stats/due/{ids}/custom/{days}",
"/v2/api/myAppName/stats/{ids}/{period}",
"/v2/api/myAppName",
"/v2/api/myAppName/summarize",
"/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
and elements not expected:
<["/api/myAppName",
"/api/myAppName/eventTypes",
"/api/myAppName/initialize",
"/api/myAppName/latest/{type}/{user}",
"/api/myAppName/stats/due/{ids}/custom/{days}",
"/api/myAppName/stats/due/{ids}/{period}",
"/api/myAppName/stats/orgs/most/{ids}/{period}",
"/api/myAppName/stats/orgs/{id}/{period}",
"/api/myAppName/stats/{ids}/{period}",
"/api/myAppName/stats/{ids}/{period}/{days}",
"/api/myAppName/summarize",
"/api/myAppName/{id}",
"/api/myAppName/{source}/events",
"/api/myAppName/{source}/events/batch"]>
at DocumentationDrivenValidator.validatePaths(DocumentationDrivenValidator.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at io.github.robwin.swagger.test.DocumentationDrivenValidator.validateSwagger(DocumentationDrivenValidator.java:88)
at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:75)
at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:87)
at my.com.app.definitions.MyTest.shouldFindNoDifferences(MyTest.java:58)
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:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
I think I'm missing something.
It was my carelessness that resulted to this problem but thanks to Roddy's comment I was able to notice my mistake.
In my assertj-swagger.properties file there contains assertj.swagger.pathsPrependExpected=/v2 property that causes this issue.

Failed to invoke PACT method

I have this snippet of code, while trying to create a pact file for my service, but it keeps throwing Failed to invoke pact Method. However, when I run the normal client request, it returns a json object, but when trying to run the pact test, it fails. Below is the snippet of the Test class
public class WhatPrimesTest {
#Rule
public PactProviderRuleMk2 provider = new PactProviderRuleMk2("PrimeService", "localhost", 81, this);
#Pact(provider = "PrimeService", consumer = "PrimeServiceClient")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap();
headers.put("Content-Type", "application/json");
DslPart etaResults = new PactDslJsonBody()
.stringType("requestedGtin", "4211")
.integerType("nodeId", 6132)
.eachLike("gtinList")
.eachArrayLike("AVAILABLE", 4322)
.asBody();
return builder
.given("There is a prime gtin 4211 from node 6132")
.uponReceiving("A request for gtinList")
.path("/primeService/6132?upc=4211")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body(etaResults).toPact();
}
#Test
#PactVerification("PrimeService")
public void doTest() {
System.setProperty("pact.rootDir", "../pacts"); // Change output dir for generated pact-files
String gtinExpected = "00000000012348";
String gtinList = new WhatPrime(provider.getPort()).checkEta(6132, "4211");
System.out.println("According to test eta=" + gtinList);
//assertTrue(gtinList.);
//assertArrayEquals("00000000012348", gtinExpected);
}
}
And I get this error when I try to run this test code.
java.lang.RuntimeException: Failed to invoke pact method
at au.com.dius.pact.consumer.BaseProviderRule.getPacts(BaseProviderRule.java:188)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:63)
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)
Caused by: java.lang.reflect.InvocationTargetException
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 au.com.dius.pact.consumer.BaseProviderRule.getPacts(BaseProviderRule.java:186)
... 16 more
Caused by: java.lang.NoSuchMethodError: au.com.dius.pact.model.matchingrules.Category.addRule(Ljava/lang/String;Lau/com/dius/pact/model/matchingrules/MatchingRule;)V
at au.com.dius.pact.consumer.dsl.PactDslJsonBody.stringType(PactDslJsonBody.java:155)
at se.ff.bsc.WhatPrimesTest.createPact(WhatPrimesTest.java:33)
... 21 more
When my service is called, this is what I get as the return.
[ { requestedGtin: "12348", nodeId: 124, gtinList: [ "00000000012348"
], primeOnHandQuantity: { AVAILABLE: 0, CLAIMS: 0 } } ]
Do you think there is something I'm doing wrong, I need help and would appreciate whatever you can comment on. Thanks
When I remove this block of code
DslPart etaResults = new PactDslJsonBody()
.stringType("requestedGtin", "4211")
.integerType("nodeId", 6132)
.eachLike("gtinList")
.eachArrayLike("AVAILABLE", 4322)
.asBody();
and directly parse the expected body in the .body() function, I get this error message
java.net.BindException: Can't assign requested address
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at sun.net.httpserver.ServerImpl.<init>(ServerImpl.java:100)
at sun.net.httpserver.HttpServerImpl.<init>(HttpServerImpl.java:50)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(DefaultHttpServerProvider.java:35)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:130)
at au.com.dius.pact.consumer.MockHttpServer.<init>(MockHttpServer.kt:206)
at au.com.dius.pact.consumer.MockHttpServerKt.mockServer(MockHttpServer.kt:34)
at au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest(ConsumerPactRunner.kt:12)
at au.com.dius.pact.consumer.BaseProviderRule.runPactTest(BaseProviderRule.java:148)
at au.com.dius.pact.consumer.BaseProviderRule.access$100(BaseProviderRule.java:21)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:76)
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)

Categories