How to remove custome properties from SOAPUI test case using java? - java

I have some custom properties for all the test cases in SoapUI.
I am able to delete using Groovy script step as described in below question:
How to remove Custom Properties from a SoapUI TestCase using Groovy?
testRunner.testCase.removeProperty( "Testcase_Property" );
But I wanted to delete these properties from JAVA. Below is the code I wrote:
String soapuiProjectPath = "ProjectLocation";
WsdlProject project = new WsdlProject(soapuiProjectPath);
StringToObjectMap context = new StringToObjectMap();
TestSuite testSuite = project.getTestSuiteByName("TestSuiteName");
WsdlTestSuite wsdlSuite = (WsdlTestSuite) testSuite;
List<TestCase> allTestCaseList = wsdlSuite.getTestCaseList();
for (TestCase testCase : allTestCaseList) {
WsdlTestCaseRunner testCaseRunner = new WsdlTestCaseRunner((WsdlTestCase) testCase, context);
List<TestProperty> testCasePropertyList = testCase.getPropertyList();
for (TestProperty testProperty : testCasePropertyList) {
WsdlTestRunContext runContext = testCaseRunner.getRunContext();
runContext.removeProperty(testProperty.getName());
}
}
System.out.println("Completed execution.");
project.save();
It is not throwing any exception. But not actually removing the custom properties as well.

Because you've to apply the removeProperty in WsdlTestCase not in WsdlTestRunContext. You can change your testCase loop code for something like:
for(TestCase testCase : allTestCaseList) {
List<TestProperty> testCasePropertyList = testCase.getPropertyList();
for (TestProperty testProperty : testCasePropertyList) {
((WsdlTestCase) testCase).removeProperty(testProperty.getName());
}
}
Hope it helps,

Related

How to Mock file array using PowerMockito?

I have the below static method in my Configs class which I am trying to Mock using Powermockito.
Ln 1 public static method getConfigs(){
2
3 File[] files = new File(/tmp/dir/).listFiles();
4 if (null == files) {
5 return Collections.emptyMap();
6 }
7 return getData();
}
And in my test class:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Configs.class)
public class ConfigsTest {
#InjectMocks
Configs configs;
#Test
public void testGetConfigs() throws Exception {
PowerMockito.mockStatic(Configs.class);
Map<String, Object> map = new HashMap<>();
map.put("data", "data");
File file = PowerMockito.mock(File.class);
File[] files = new File[] { new File("file") };
PowerMockito.when(file.listFiles()).thenReturn(files);
PowerMockito.when(configs.getDataMap()).thenReturn(map);
Map data = secrets.getDataMap();
Assert.assertNotNull(data);
}
Now, the issue is that the test fails at the IF condition, line 4. I tried several ways to mock and add value to the file object used in the null check. I need my tests to cover beyond the IF condition to meet sonar coverage. Please let me know how I could achieve this.
I think it should be like this
PowerMockito.mockStatic(Configs.class);
PowerMockito.when(Configs.getConfigs()).thenReturn(map);
powermock-static

How to get #tag from an excel file to CucumberOptions in Selenium java

Normally I would write a cucumber option as below:
#CucumberOptions(
features = "src\\main\\java\\feature"
, glue= "stepdefination",
plugin= {"com.cucumber.listener.ExtentCucumberFormatter:Report/Report.html"}
tags="#tag, #tag1, #sort"
)
public class TestRunner extends TestFunction {
#Test
public void runcukes( ) {
new TestNGCucumberRunner(getClass()).runCukes();
}
#BeforeClass
public void tags() {
}
#AfterClass
public void writeExtentReport() {
Reporter.loadXMLConfig("extent-config.xml");
}
}
My question is: How can I fetch #tag, #tag1, #sort from an excel file to #cucmberoptions and run the program in Selenium Java?
I am not sure about using cucumber options but by using cucumber RuntimeOptions class you can achieve it. The below method needs to be called in a loop that means you have 10 tags to execute then call this method in for loop.
public static boolean cucumberRun(String tag) {
try {
ClassLoader classLoader = CustomClass.class.getClassLoader();
ResourceLoader resourceLoader = new MultiLoader(classLoader);
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
/* Adding cucumber plugins */
List<String> pluginList = new ArrayList<String>();
pluginList.add("--plugin");
pluginList.add("html:target/cucumber-html-report");
pluginList.add("--plugin");
pluginList.add("json:target/cucumber.json");
pluginList.add("--plugin");
pluginList.add("com.cucumber.listener.ExtentCucumberFormatter:");
pluginList.add("--plugin");
pluginList.add("rerun:target/failedScenarios.txt");
/* Location for BDD extent report. */
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath("location/Extent_report.html");
/*
* Adding cucumberOptions.
*
* You can get the tag value from excel and pass it here. We need to add # before tag value.
*/
RuntimeOptions ro = new RuntimeOptions(pluginList);
ro.getFilters().add("#"+tag);
ro.getFeaturePaths().add("location of feature files");
ro.getGlue().add("location of glue code");
/* Loads all the resources into Cucumber RunTime class and execute. */
cucumber.runtime.Runtime runtime = new cucumber.runtime.Runtime(resourceLoader, classFinder, classLoader,
ro);
runtime.run();
}catch(Exception e){
// Handle exception
}

How to print full path to script files in #sql annotation in spring boot test

In a multi-module project I want to be sure that Spring's #sql annotation uses correct resources. Is there a way to log full path of those files to console somehow?
Spring does log script file name before execution, but in tests for different modules those file names are the same sometimes.
SqlScriptsTestExecutionListener - responsible for the processing of #Sql, for the first step you can change to debug related log by adding property logging.level.org.springframework.test.context.jdbc=debug, but the debug message is not fully and if is not enough you should create your own TestExecutionListener and declare on test class #TestExecutionListeners(listeners = SqlScriptsCustomTestExecutionListener.class)
for example:
public class SqlScriptsCustomTestExecutionListener extends AbstractTestExecutionListener {
#Override
public void beforeTestMethod(TestContext testContext) {
List<Resource> scriptResources = new ArrayList<>();
Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(testContext.getTestMethod(), Sql.class);
for (Sql sqlAnnotation : sqlAnnotations) {
String[] scripts = sqlAnnotation.scripts();
scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
scriptResources.addAll(TestContextResourceUtils.convertToResourceList(testContext.getApplicationContext(), scripts));
}
if (!scriptResources.isEmpty()) {
String debugString = scriptResources.stream().map(r -> {
try {
return r.getFile().getAbsolutePath();
} catch (IOException e) {
System.out.println("Unable to found file resource");
}
return null;
}).collect(Collectors.joining(","));
System.out.println(String.format("Execute sql script :[%s]", debugString));
}
}
It is just quick example and it works. Most of source code i copied from SqlScriptsTestExecutionListener just for explanation. It is just realization in case of #Sql annotation on method level, and not included class level.
I hope it will be helps you.

Create TestNG.xml file dynamically and pass parameter

I have to execute test scripts using dynamic testng.xml file which means I have to create testng.xml file thru code and pass the parameters to the #Test methods pro grammatically.
For that I have created two Java files DynamicTestNG.java which should generate testng.xml file and run SampleClass.java where the #Test method has been written along with the parameters.
DynamicTestNG.java
public class DynamicTestNG {
public void runTestNGTest(Map<String,String> testngParams) {
//Create an instance on TestNG
TestNG myTestNG = new TestNG();
//Create an instance of XML Suite and assign a name for it.
XmlSuite mySuite = new XmlSuite();
mySuite.setName("MySuite");
//Create an instance of XmlTest and assign a name for it.
XmlTest myTest = new XmlTest(mySuite);
myTest.setName("MyTest");
//Add any parameters that you want to set to the Test.
myTest.setParameters(testngParams);
//Create a list which can contain the classes that you want to run.
List<XmlClass> myClasses = new ArrayList<XmlClass> ();
myClasses.add(new XmlClass("SampleClass"));
//Assign that to the XmlTest Object created earlier.
myTest.setXmlClasses(myClasses);
//Create a list of XmlTests and add the Xmltest you created earlier to it.
List<XmlTest> myTests = new ArrayList<XmlTest>();
myTests.add(myTest);
//add the list of tests to your Suite.
mySuite.setTests(myTests);
//Add the suite to the list of suites.
List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
mySuites.add(mySuite);
//Set the list of Suites to the testNG object you created earlier.
myTestNG.setXmlSuites(mySuites);
TestListenerAdapter tla = new TestListenerAdapter();
myTestNG.addListener(tla);
//invoke run() - this will run your class.
myTestNG.run();
}
public static void main (String args[])
{
DynamicTestNG dt = new DynamicTestNG();
//This Map can hold your testng Parameters.
Map<String,String> testngParams = new HashMap<String,String> ();
testngParams.put("searchtext1", "testdata1");
testngParams.put("searchtext2", "testdata2");
dt.runTestNGTest(testngParams);
}
}
And SampleClass.java
public class SampleClass {
private WebDriver driver;
#BeforeTest
public void setUp()
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\AK5040691\\Desktop\\IE driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://executeautomation.com/blog/custom-testng-library-for-appium/#more-1562");
}
//#Parameters({"searchText1","searchText2"})
//#Test
public void searchText(String text1, String text2)
{
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.className("search-field")).sendKeys(text1);
driver.findElement(By.className("search-field")).clear();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.className("search-field")).sendKeys(text2);
}
}
Its not running. Please let me know the mistake here.
You have to uncomment the #Test annotation in your SampleClass file. And if your SampleClass is in a package , then absolute package name + class name is to be specified in this statement.
myClasses.add(new XmlClass("com.some.package.SampleClass"));
Generally TestNG classes have a suffix or prefix labelled "Test" so that surefire plugin can include them in the execution flow, in case if you are using maven.
You can instead use the constructor with parameter of class object .
myClasses.add(new XmlClass(SampleClass.class));

Spring Boot can't run single test in IntelliJ

This started happening recently, but I'm not sure what changed to cause it.
When I run all tests from IntelliJ, all is well. Also the gradle build is fine.
When I run a single unit test, all is well.
When I run a single web integration test, it fails because a config class has all null properties.
The config class looks like (Kotlin):
#Component
#ConfigurationProperties(prefix = "api")
public open class ApiConfigImpl : ApiConfig
{
A test looks like:
#RunWith(SpringJUnit4ClassRunner::class)
#ContextConfiguration(classes = arrayOf(ApplicationAssembly::class), loader = SpringApplicationContextLoader::class)
#WebIntegrationTest
open class CandidateProfileControllerTest
{
#Inject lateinit var profileRepo: CandidateProfileRepository
//etc a few more deps used to setup test data
#Test
open fun getById()
{
val greg = CandidateProfile("123", "12312", "Greg", "Jones", dateOfBirth = Date(), gender = Gender.MALE,
biography = "ABC", maxMatchableAge = null, maxMatchableDistance = null)
profileRepo.save(greg)
val auth = given().header("content-type", "application/json")
.body(testCredentials)
.post("/authorization/social").peek().asString()
val accessToken: String = from(auth).get("accessToken")
given().header("Access-Token", accessToken).
header("API-Key", testAPIKey()).
get("/profile/${greg.id}").
peek().then().
body("stageName", notNullValue())
}
I'm not sure what information I can add. Based on the limited information provided:
Is this a known problem with a known solution?
This is a bug, logged in the IntelliJ/Kotlin tracker, with a pending fix.

Categories

Resources