"No tests found matching Method " error on CDC test with spring and pact - spring-test

I doing an CDC provider test with pact and spring, I was able to generate the pact file,
but when I use the pact json for provider testing , it came out below error :"No tests found matching Method runTest", here is my code:
#RunWith(SpringRestPactRunner.class)
#Provider("myProvider")
#PactFolder("target/pacts")
#WebMvcTest(MyController.class)
public class ProviderTest {
#InjectMocks
private MyController myController; # the controller I want to test
#MockBean
private MyService myService; # the dependency of controller
#TestTarget
public final Target target = new SpringBootHttpTarget();
#State("my_state")
public void runTest() {
}
}
and the pact file is something like this:
... other parts
"providerStates": [
{
"name": "my_state"
}
]
... other parts
it seems that my test cannot find the "my_state" ?
EDIT:
here is my demo project , Please help take a look, Thanks!
https://github.com/wuhuanxing/pact_demo

That pact is using version 3 of the pact specification. Make sure you're using the latest version of the pact jar to ensure it supports version 3. If you can create a reproducible example in a Github repository, you can ask for help on slack.pact.io.

Related

Mockito how can simule record doesn't exist

.exception.INSSTaxNotFoundException: INSS Tax not found with ID 1
Could someone help me?
I want mokite "inssTaxService.findById", I don't know how do.
I get this error: INSSTaxNotFoundException: INSS Tax not found with ID 1.
But I could like found the record and go on.
Can I do that in Service or Not?
#Test
void whenINSSTaxIdInformedThenReturnThisINSSTax() throws INSSTaxNotFoundException {
INSSTaxDTO expectedSavedInssTaxDTO = INSSTaxBuilder.builder().build().toINSSTaxDTO();
INSSTax expectedSavedInssTax = inssTaxMapper.toModel(expectedSavedInssTaxDTO);
when(inssTaxService.findById(expectedSavedInssTaxDTO.getId())).
thenReturn(expectedSavedInssTaxDTO);
assertEquals(expectedSavedInssTax.getId(), expectedSavedInssTaxDTO.getId());
assertEquals(expectedSavedInssTax.getDescription(), expectedSavedInssTaxDTO.getDescription());
assertEquals(expectedSavedInssTax.getSocialSecurityRatePercent(), expectedSavedInssTaxDTO.getSocialSecurityRatePercent());
}
What you might be missing is actually injecting the mock of inssTaxService inside your class which you are testing,
Your code would be something like this. Considering its a pure java code(not spring boot etc, you can change the code accordingly in that case).
Mock the service(Which i feel you have done else Mockito would have thrown and error)
InssTaxService mockedInssTaxService = Mockito.mock(InssTaxService.class);
//other impl on this mock for this e.g
when(mockedInssTaxService.findById(expectedSavedInssTaxDTO.getId())).
thenReturn(expectedSavedInssTaxDTO);
Inject the mocked object to the ClassToTest.
ClassToTest classToTest = new ClassToTest(mockedInssTaxService);
If you are using spring boot test you can use #MockBean or #Mock and #InjectMocks instead of new keyword

Objenesis dependency causes instantiation error

Just starting a new Gradle project.
This test passes:
def 'Launcher.main should call App.launch'(){
given:
GroovyMock(Application, global: true)
when:
Launcher.main()
then:
1 * Application.launch( App, null ) >> null
}
... until, to get another test using a (Java) Mock to work, I have to add these dependencies:
testImplementation 'net.bytebuddy:byte-buddy:1.10.8'
testImplementation 'org.objenesis:objenesis:3.1'
(NB I assume these versions are OK for Groovy 3.+, which I'm now using ... both are the most up-to-date available at Maven Repo).
With these dependencies the above test fails:
java.lang.InstantiationError: javafx.application.Application
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.objenesis.ObjenesisHelper.newInstance(ObjenesisHelper.java:44)
at org.spockframework.mock.runtime.MockInstantiator$ObjenesisInstantiator.instantiate(MockInstantiator.java:45)
at org.spockframework.mock.runtime.MockInstantiator.instantiate(MockInstantiator.java:31)
at org.spockframework.mock.runtime.GroovyMockFactory.create(GroovyMockFactory.java:57)
at org.spockframework.mock.runtime.CompositeMockFactory.create(CompositeMockFactory.java:42)
at org.spockframework.lang.SpecInternals.createMock(SpecInternals.java:47)
at org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:298)
at org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:288)
at org.spockframework.lang.SpecInternals.GroovyMockImpl(SpecInternals.java:215)
at core.AppSpec.Launcher.main should call App.launch(first_tests.groovy:30)
I confess that I have only the sketchiest notion of what "bytebuddy" and "objenesis" actually do, although I assume it is fiendishly clever. Edit: having just visited their respective home pages my notion is now slightly less sketchy, and yes, it is fiendishly clever.
If an orthodox solution to this is not available, is it by any chance possible to turn off the use of these dependencies for an individual feature (i.e. test)? Possibly using some annotation maybe?
Edit
This is an MCVE:
Specs: Java 11.0.5, OS Linux Mint 18.3.
build.gradle:
plugins {
id 'groovy'
id 'java'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.8'
}
repositories { mavenCentral() }
javafx {
version = "11.0.2"
modules = [ 'javafx.controls', 'javafx.fxml' ]
}
dependencies {
implementation 'org.codehaus.groovy:groovy:3.+'
testImplementation 'junit:junit:4.12'
testImplementation 'org.spockframework:spock-core:2.0-M2-groovy-3.0'
testImplementation 'net.bytebuddy:byte-buddy:1.10.8'
testImplementation 'org.objenesis:objenesis:3.1'
// in light of kriegaex's comments:
implementation group: 'cglib', name: 'cglib', version: '3.3.0'
}
test { useJUnitPlatform() }
application {
mainClassName = 'core.Launcher'
}
installDist{}
main.groovy:
class Launcher {
static void main(String[] args) {
Application.launch(App, null )
}
}
class App extends Application {
void start(Stage primaryStage) {
}
}
first_tests.groovy:
class AppSpec extends Specification {
def 'Launcher.main should call App.launch'(){
given:
GroovyMock(Application, global: true)
when:
Launcher.main()
then:
1 * Application.launch( App, null ) >> null
}
}
The reason why this project needs something to call the Application subclass is explained here: it's so that it is possible to do an installDist which bundles in JavaFX.
Don't we have to use a global GroovyMock?
If you want to check the interaction, yes. But actually you are testing the JavaFX launcher rather than your application. So I doubt that there is any benefit. I would focus on testing the App class instead. Also imagine for a moment that you would write the classes with main methods in Java instead of Groovy. Groovy mocks would not work when called from Java code, especially not global ones. Then you would end up testing via Powermockito from Spock, which would also work but still you would test the JavaFX launcher rather than your application.
Also isn't it slightly extreme to say any use of Groovy mocks is wrong?
I did not say that. I said: "probably something is wrong with your application design". The reason I said that is because the use of Groovy mocks and things like mocking static methods are test code smells. You can check the smell and then decide it is okay, which IMO in most cases it is not. Besides, instead of application design the problem can also be in the test itself, which in this case I would say it is. But that is arguable, so I am going to present a solution to you further below.
In this case technically the global Application mock is your only way if you do insist to test the JavaFX launcher because even a global mock on App would not work as the launcher uses reflection in order to call the App constructor and that is not intercepted by the mock framework.
you say that Spock spock-core:2.0-M2-groovy-3.0 is a "pre-release". I can't see anything on this page (...) which says that. How do you know?
You found out already by checking out the GitHub repository, but I was just seeing it in the unusual version number containing "M2" like "milestone 2" which is similar to "RC" (or "CR") for release candidates (or candidate releases).
As for the technical problem, you can either not declare Objenesis in your Gradle script because it is an optional dependency, then the test compiles and runs fine, as you already noticed yourself. But assuming you need optional dependencies like Objenesis, CGLIB (actually cglib-nodep), Bytebuddy and ASM for other tests in your suite, you can just tell Spock not to use Objenesis in this case. So assuming you have a Gradle build file like this:
plugins {
id 'groovy'
id 'java'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.8'
}
repositories { mavenCentral() }
javafx {
version = "11.0.2"
modules = ['javafx.controls', 'javafx.fxml']
}
dependencies {
implementation 'org.codehaus.groovy:groovy:3.+'
testImplementation 'org.spockframework:spock-core:2.0-M2-groovy-3.0'
// Optional Spock dependencies, versions matching the ones listed at
// https://mvnrepository.com/artifact/org.spockframework/spock-core/2.0-M2-groovy-3.0
testImplementation 'net.bytebuddy:byte-buddy:1.9.11'
testImplementation 'org.objenesis:objenesis:3.0.1'
testImplementation 'cglib:cglib-nodep:3.2.10'
testImplementation 'org.ow2.asm:asm:7.1'
}
test { useJUnitPlatform() }
application {
mainClassName = 'de.scrum_master.app.Launcher'
}
installDist {}
My version of your MCVE would looks like this (sorry, I added my own package names and also imports because otherwise it is not really an MCVE):
package de.scrum_master.app
import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.control.Label
import javafx.scene.layout.StackPane
import javafx.stage.Stage
class App extends Application {
#Override
void start(Stage stage) {
def javaVersion = System.getProperty("java.version")
def javafxVersion = System.getProperty("javafx.version")
Label l = new Label("Hello, JavaFX $javafxVersion, running on Java $javaVersion.")
Scene scene = new Scene(new StackPane(l), 640, 480)
stage.setScene(scene)
stage.show()
}
}
package de.scrum_master.app
import javafx.application.Application
class Launcher {
static void main(String[] args) {
Application.launch(App, null)
}
}
package de.scrum_master.app
import javafx.application.Application
import spock.lang.Specification
class AppSpec extends Specification {
def 'Launcher.main should call App.launch'() {
given:
GroovyMock(Application, global: true, useObjenesis: false)
when:
Launcher.main()
then:
1 * Application.launch(App, null)
}
}
The decisive detail here is the useObjenesis: false parameter.
Update: Just for reference, this is how you would do it with a launcher class implemented in Java using PowerMockito.
Attention, this solution needs the Sputnik runner from Spock 1.x which was removed in 2.x. So in Spock 2 this currently does not work because it is based on JUnit 5 and can no longer use #RunWith(PowerMockRunner) and #PowerMockRunnerDelegate(Sputnik) because PowerMock currently does not support JUnit 5. But I tested it with Spock 1.3-groovy-2.5 and Groovy 2.5.8.
package de.scrum_master.app
import javafx.application.Application
import org.junit.runner.RunWith
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import org.powermock.modules.junit4.PowerMockRunnerDelegate
import org.spockframework.runtime.Sputnik
import spock.lang.Specification
import static org.mockito.Mockito.*
import static org.powermock.api.mockito.PowerMockito.*
#RunWith(PowerMockRunner)
#PowerMockRunnerDelegate(Sputnik)
#PrepareForTest(Application)
class JavaAppSpec extends Specification {
def 'JavaLauncher.main should launch JavaApp'() {
given:
mockStatic(Application)
when:
JavaLauncher.main()
then:
verifyStatic(Application, times(1))
Application.launch(JavaApp)
}
}

My first basic Cucumber program (Scenario) fails - Java

I wrote my first Cucumber program today, and it fails. I wrote a very basic one, a simple scenario and it's step definition. Below is the feature file code and the step definition code.
Step Definiton code:
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
public class Testing_Example1 {
#When("^I am on x page$")
public void i_am_on_x_page() throws Throwable {
System.out.println("I am on xPage");
}
#Then("^I see that element$")
public void i_see_that_element() throws Throwable {
System.out.println("I can see that page");
}
}
Feature File Code:
Feature: Testing
Scenario: s1
When I am on x page
Then I see that element
I have added the system variables as well - The JAVA_HOME and the maven variables as well and linked it to the PATH variable I system variables.
I have added dependencies in the POM file, such as the Cucumber-Java, Cucumber-Junit and for selenium as well and yet my program fails and says the steps are undefined.
Output:
1 Scenarios (1 undefined)
2 Steps (2 undefined)0m0.000s
You can implement missing steps with the snippets below:
#When("^I am on x page$")
public void i_am_on_x_page() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^I see that element$")
public void i_see_that_element() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
Undefined step: When I am on x page
Undefined step: Then I see that element
Process finished with exit code 0
I guess it's because my feature file is not getting linked with the step definition file, but I don't understand what is missing that the feature file does not execute properly and scenarios fail. Someone who has knowledge about this, do help.
Thank You!
I found the solution to this. I just edited the configuration of the feature file - > edit configurations -> Paste the path of the package in which your step definition file is present -> apply.
I just has to link the feature file to the step definition using Glue.
Specify the stepdefintion & feature file details in your cucumber runner class.
#CucumberOptions(
plugin={"pretty", "html:target/cucumber-html-report","json:target/cucumber-report.json"},
features = "src/test/resources",
glue ="com.vg.pw.ui.stepdefinitions",
)
public class CucumberRunner {
...
}

How to inject or import libraries in the tapestry core stack to a component?

I'm using tapestry 5.4.1. I have a component with a module that requires prototype. I know prototype is available in the core stack. However how do I import this as a dependency.
My module:
define(["prototype"], function(container, link) {
return new Ajax.PeriodicalUpdater(container, link, {
method : 'post', frequency : 5, decay : 1
});
});
I tried adding this to the class but the path cannot be resolved
#Import(library = {"prototype.js"})
public class Update {
Tried injecting the asset and adding it to the environmental javascriptsupport but it somehow looks for it in the wrong location.
#Inject
#Path("classpath:META-INF/assets/tapestry5/prototype.js")
private Asset prototype;
and
javascriptSupport.importJavaScriptLibrary(prototype);
javascriptSupport.require("update").with(container, getLink());
I don't want to hard code the url with the generated hash.
/assets/meta/z67bxxxx/tapestry5/scriptaculous_1_9_0/prototype.js
Anything I am missing here? Any help would be appreciated.
Make sure you define correct infrastructure in your AppModule
#ApplicationDefaults
public static void contributeApplicationDefaults(MappedConfiguration<String, Object> configuration) {
configuration.add(SymbolConstants.JAVASCRIPT_INFRASTRUCTURE_PROVIDER, "prototype");
}
You don't have to specify dependency clearly ["prototype"].

Trying "Messaging via attribute" from the documentation

I'm trying to get the hung of catel but have a problem.
Trying "Messaging via attribute" gets an compile error.
'Catel.MVVM.ViewModelBase.GetService(object)' is obsolete: 'GetService is no longer >recommended. It is better to inject all dependencies (which the TypeFactory fully supports) >Will be removed in version 4.0.0.'
private void OnCmdExecute()
{
var mediator = GetService<IMessageMediator>();
mediator.SendMessage("Test Value");
}
[MessageRecipient]
private void ShowMessage(string value)
{
var messageService = GetService<IMessageService>();
messageService.Show(value);
}
I'm using 3.9.
A hint and a code snippet whould be good help.
Thanks for your attention.
The GetService is marked obsolete. You have 2 options:
1) If you are using a view model, simply let the services be injected in the constructor:
private readonly IMessageMediator _messageMediator;
private readonly IMessageService _messageService;
public MyViewModel(IMessageMediator messageMediator, IMessageService messageService)
{
Argument.IsNotNull(() => messageMediator);
Argument.IsNotNull(() => messageService);
_messageMediator = messageMediator;
_messageService= messageService;
}
2) Use the GetDependencyResolver extension method:
var dependencyResolver = this.GetDependencyResolver();
var messageMediator = dependencyResolver.Resolve<IMessageMediator>();
Solution 1 is the recommended way.
Thanks for your answer.
I also found a good example in the "Catel.Examples" solution, link to download

Resources