I have test
#Test
public void myTest() {
Results results = Runner.path("classpath:features/myFeature.feature").parallel(1);
Assert.assertEquals(results.getErrorMessages(), 0, results.getFailCount());
}
Feature looks like this
* def myVariable =
"""
function(x, y)
{
functionBody...
}
"""
Scenario: My scenario
* kafkaClient.publish(...)
* def result = myVariable(...)
And assert result != null
I installed karate plugin, now in feature I see the syntax highlighting, however there is no ability to put breakpoint in feature.
I use karate version 1.2.0
How I can debug features? I want to stop at (* def result) line for example, or I want to debug js function (functionBody...). Is there any proper way to do so?
Right now you can debug a feature file if you use the run-configuration as shown in this video: https://youtu.be/w6V8rKOtyyg
We don't yet support debugging in JS blocks.
You need to be on the paid version of the plugin for feature-file debugging to work.
Related
In JavaScript, the library Jest has a delightful semantic - expect.assertions(number) which verifies that a certain number of assertions are called during a test, for example of async code:
test('doAsync calls both callbacks', () => {
expect.assertions(2);
function callback1(data) {
expect(data).toBeTruthy();
}
function callback2(data) {
expect(data).toBeTruthy();
}
doAsync(callback1, callback2);
});
Is there a similar semantic available in JUnit or other Java unit testing libraries?
If so, please feel very welcome to give an example, such as using CompleteableFuture or as appropriate.
I write a test case to test for my service (has Method Under Test - MUT) using TestNG, Mockito-inline (to mock static). My issue is: when I set breakpoints at MUT then Eclipse's cursor cannot stop at these breakpoints. If set breakpoints at test code, the cursor stop and highlight correctly.
I tried to back to Mockito-core (but cannot use Mockito-static anymore, same version 3.11.2) then every breakpoints (in test code and in my service) work correctly.
Here is detail:
A test case: Breakpoints at this test file work correctly
try (MockedStatic<myClass> mockMyClass = Mockito.mockStatic(myClass.class)) {
mockMyClass.when(() -> myClass.get(anyInt()).thenReturn(myReturnObject);
myService.myMethodUnderTest();
}
My service code: another file (myService) has many methods (these methods - myMethodUnderTest call the static method myClass.get(int value))
public void myMethodUnderTest(int value) {
line 1; // if set breakpoint here, Eclipse's cursor does not stop, everything works
normally as without this breakpoint. This code line must be run without any
conditions
myClass.get(value); // the static mock works correctly
line n; // If set breakpoint -> the same line 1
}
Here is my detail environment: Ubuntu 20.04, Eclipse 2018-12, Java 1.8, Spring 5.1.9, TestNG 7.4.0, Mockito 3.11.2 (core and inline)
I tried to use Mockito-inline 3.8.0 but the same issue.
When I debug step by step (F5, F6) the Eclipse'cursor is not correct (still highlight a line but wrong logic) when running in the method under test too (still correct when running in the test code).
Anyone can help to resolve this issue, run debug step by step correctly with Mockito-inline.
Thank you very much
Executing the gradle application plugin's installDist task creates a directory build/install/my-application-name/bin that contains wrapper scripts, my-application-name and my-application-name.bat. Running either of these scripts runs the application, and arguments passed to these scripts are passed to the underlying application.
In UNIX shell scripts you can access the name that was used to execute the program as $0. In fact, the UNIX version of the gradle-generated startup script uses $0 several times.
How can I configure the gradle application plugin such that these scripts will pass the value of $0 (and whatever the Windows equivalent is on Windows) into the underlying application, perhaps as a Java system property?
Since parameter for obtaining the name of the script being run is referenced differently in Linux($0) and in Windows(%0), the most straightforward way to generate custom scripts would be to use separate custom templates for the respective start script generators:
startScripts {
unixStartScriptGenerator.template = resources.text.fromFile('unixStartScript.txt')
windowsStartScriptGenerator.template = resources.text.fromFile('windowsStartScript.txt')
}
The default templates are easy to obtain invoking e.g. unixStartScriptGenerator.template.asString()
Documentation on customizing the start scripts can be found here.
This is what I ended up doing, based on jihor's answer. I'm posting it here just so that there's a working answer for anyone else interested:
startScripts {
def gen = unixStartScriptGenerator
gen.template = resources.text.fromString(
gen.template.asString().replaceFirst('(?=\nDEFAULT_JVM_OPTS=.*?\n)') {
'\nJAVA_OPTS="\\$JAVA_OPTS "\'"-Dprogname=\\$0"\''
})
// TODO: do something similar for windowsStartScriptGenerator
}
This uses replaceFirst is instead of replace so we can match a pattern. This is a little less brittle, and also lets us use lookahead so we don't have to actually replace what we're looking for. (This is groovy's variant of replaceFirst that takes a closure, by the way. This requires far less escaping than the version that takes a replacement string in this case.)
Also, instead of:
JAVA_OPTS="$JAVA_OPTS -Dprogname=$0"
we actually need something like:
JAVA_OPTS="$JAVA_OPTS "'"-Dprogname=$0"'
This is because $0 may contains special character (like spaces), and the startup script removes one level of quoting in the value of $JAVA_OPTS using eval set --.
(If anyone knows how to make this work on Windows, pleas feel free to update this answer.)
I took an alternative approach. According to the documentation, as far back as Gradle 2.4 and all the way through Gradle 4.8, we should be able to set the following properties within the startScripts task:
applicationName
optsEnvironmentVar
exitEnvironmentVar
mainClassName
executableDir
defaultJvmOpts
appNameSystemProperty
appHomeRelativePath
classpath
Unfortunately, this is not true for the following properties, which seem to have never been exposed:
appNameSystemProperty
appHomeRelativePath
If appNameSystemProperty were exposed as the documentation describes, then we should be able to simply do the following:
startScripts {
applicationName = 'foo'
appNameSystemProperty = 'appName'
}
This would then result in the addition of -DappName=foo to the Java command constructed within both of the start scripts.
Since this is not the case, I took the following approach, which is a bit more verbose than the earlier solution to this question, but is perhaps less brittle because it does not rely on tweaking the out-of-box templates. Instead, it results in the documented behavior.
startScripts {
mainClassName = '...'
applicationName = 'foo'
unixStartScriptGenerator =
new CustomStartScriptGenerator(generator: unixStartScriptGenerator)
windowsStartScriptGenerator =
new CustomStartScriptGenerator(generator: windowsStartScriptGenerator)
}
class CustomStartScriptGenerator implements ScriptGenerator {
#Delegate
ScriptGenerator generator
void generateScript(JavaAppStartScriptGenerationDetails details,
Writer destination) {
details = new CustomDetails(details: details)
this.generator.generateScript(details, destination)
}
static class CustomDetails implements JavaAppStartScriptGenerationDetails {
#Delegate
JavaAppStartScriptGenerationDetails details
#Override
String getAppNameSystemProperty() { 'appName' }
}
}
I am new to Groovy and am trying to set up a postbuild in Jenkins that allows me to count strings and determine if the build succeeded by how many the count returns at the end.
Here is my example code :
class Main {
def manager = binding.getVariable("manager")
def log = manager.build.logFile.text
def list = log
def JobCount = list.count {it.startsWith("====") && it.contains("COMPLETE")}
if (JobCount == 7) {
manager.listener.logger.println("All Jobs Completed Successfully")
} else {
manager.addWarningBadge("Not All Jobs Have Completed Successfully")
manager.buildUnstable()
}
}
I am looking for a specific string that gets printed to the console when the test has completed successfully. The string is "====JOB COMPLETE====" and I should have 7 instances of this string if all 7 tests passed correctly.
Currently when I run this code I get the following error :
Script1.groovy: 6: unexpected token: if # line 6, column 5.
if (JobCount == 7)
^
Any help would be greatly appreciated
manager.build.logFile.text returns the whole file text as String.
What you need is readLines():
def list = manager.build.logFile.readLines()
def JobCount = list.count {it.startsWith("====") && it.contains("COMPLETE")}
and of course as mentioned below, the Jenkins Groovy Postbuild plugin runs Groovy scripts, so you will have get rid of the enclosing class declaration (Main)
You have statements directly inside your class, without being in a method, which is not allowed in Java/Groovy. Since this is Groovy, you can run this as a script without the class at all, or put the offending code (the if statement) inside a method and call the method.
Perhaps you're missing a closing }
def JobCount = list.count {it.startsWith("====") && it.contains("COMPLETE")}
I'm quite new to WebDriver and TestNG framework. I've started with a project that does a regression test of an e-commerce website. I'm done with the login and registration and so on. But there is something that I don't quite understand.
Example, I have this easy code that searches for a product.
driver.get(url + "/k/k.aspx");
driver.findElement(By.id("q")).clear();
driver.findElement(By.id("q")).sendKeys("xxxx"); //TODO: Make this dynamic
driver.findElement(By.cssSelector("input.submit")).click();
Now I want to check if xxxx is represented on the page. This can be done with
webdriver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*xxxxxx[\\s\\S]*$")
I store this in a Boolean and check if its true or false.
Now to the question, based on this Boolean value I want to say that the test result is success or fail. How can I do that? What triggers a testNG test to fail?
TestNG or any other testing tool decides success or failure of a test based on assertion.
Assert.assertEquals(actualVal, expectedVal);
So if actualVal and expectedVal are same then test will pass else it will fail.
Similarly you will find other assertion options if you using any IDE like Eclipse.
If you want to stop your test execution based on the verification of that text value, then you can use Asserts. However, if you want to log the outcome of the test as a failure and carry on, you should try using soft assertions, which log the verification as passed or failed and continue with the test. Latest Testng comes equipped to handle this - info at Cedric's blog
write this code where your if condition fails
throw new RuntimeException("XXXX not found: ");
u can use throw exception, and each method which will cal this meth should also throw Excetion after method name or you can use try catch. sample:
protected Boolean AssertIsCorrectURL(String exedctedURL) throws Exception {
String errMsg = String.format("Actual URL page: '%s'. Expected URL page: '%s'",
this.driver.getCurrentUrl(), exedctedURL);
throw new Exception(errMsg);
}
You can do this.
boolean result = webdriver.findElement(By.cssSelector("BODY")).getText().matches("^[\s\S]xxxxxx[\s\S]$")
Assert.assertTrue(result);