Best Citrus code snippet using com.consol.citrus.actions.ExecuteSQLQueryAction
Source:JdbcSteps.java
...20import java.util.List;21import java.util.Map;22import com.consol.citrus.Citrus;23import com.consol.citrus.TestCaseRunner;24import com.consol.citrus.actions.ExecuteSQLQueryAction;25import com.consol.citrus.annotations.CitrusFramework;26import com.consol.citrus.annotations.CitrusResource;27import com.consol.citrus.context.TestContext;28import com.consol.citrus.exceptions.CitrusRuntimeException;29import io.cucumber.datatable.DataTable;30import io.cucumber.java.Before;31import io.cucumber.java.Scenario;32import io.cucumber.java.en.Given;33import io.cucumber.java.en.Then;34import io.cucumber.java.en.When;35import org.springframework.jdbc.datasource.SingleConnectionDataSource;36import static com.consol.citrus.actions.ExecuteSQLAction.Builder.sql;37import static com.consol.citrus.actions.ExecuteSQLQueryAction.Builder.query;38import static com.consol.citrus.container.RepeatOnErrorUntilTrue.Builder.repeatOnError;39/**40 * @author Christoph Deppisch41 */42public class JdbcSteps {43 @CitrusResource44 private TestCaseRunner runner;45 @CitrusResource46 private TestContext context;47 @CitrusFramework48 private Citrus citrus;49 private DataSource dataSource;50 private final List<String> sqlQueryStatements = new ArrayList<>();51 private int maxRetryAttempts = JdbcSettings.getMaxAttempts();52 private long delayBetweenAttempts = JdbcSettings.getDelayBetweenAttempts();53 @Before54 public void before(Scenario scenario) {55 if (dataSource == null && citrus.getCitrusContext().getReferenceResolver().resolveAll(DataSource.class).size() == 1L) {56 dataSource = citrus.getCitrusContext().getReferenceResolver().resolve(DataSource.class);57 }58 }59 @Given("^SQL query retry configuration$")60 public void configureRetryConfiguration(Map<String, Object> configuration) {61 maxRetryAttempts = Integer.parseInt(configuration.getOrDefault("maxRetryAttempts", maxRetryAttempts).toString());62 delayBetweenAttempts = Long.parseLong(configuration.getOrDefault("delayBetweenAttempts", delayBetweenAttempts).toString());63 }64 @Given("^SQL query max retry attempts: (\\d+)")65 public void configureMaxRetryAttempts(int maxRetryAttempts) {66 this.maxRetryAttempts = maxRetryAttempts;67 }68 @Given("^SQL query retry delay: (\\d+)ms")69 public void configureDelayBetweenAttempts(long delayBetweenAttempts) {70 this.delayBetweenAttempts = delayBetweenAttempts;71 }72 @Given("^(?:D|d)ata source: ([^\"\\s]+)$")73 public void setDataSource(String id) {74 if (!citrus.getCitrusContext().getReferenceResolver().isResolvable(id)) {75 throw new CitrusRuntimeException("Unable to find data source for id: " + id);76 }77 dataSource = citrus.getCitrusContext().getReferenceResolver().resolve(id, DataSource.class);78 }79 @Given("^(?:D|d)atabase connection$")80 public void setConnection(DataTable properties) {81 Map<String, String> connectionProps = properties.asMap(String.class, String.class);82 String driver = connectionProps.getOrDefault("driver", "org.postgresql.Driver");83 String url = connectionProps.getOrDefault("url", "jdbc:postgresql://localhost:5432/testdb");84 String username = connectionProps.getOrDefault("username", "test");85 String password = connectionProps.getOrDefault("password", "test");86 boolean suppressClose = Boolean.parseBoolean(connectionProps.getOrDefault("suppressClose", Boolean.TRUE.toString()));87 SingleConnectionDataSource singleConnectionDataSource = new SingleConnectionDataSource(88 context.replaceDynamicContentInString(url),89 context.replaceDynamicContentInString(username),90 context.replaceDynamicContentInString(password), suppressClose);91 singleConnectionDataSource.setDriverClassName(context.replaceDynamicContentInString(driver));92 this.dataSource = singleConnectionDataSource;93 }94 @Given("^SQL query: (.+)$")95 public void addQueryStatement(String statement) {96 if (statement.trim().toUpperCase().startsWith("SELECT")) {97 sqlQueryStatements.add(statement);98 } else {99 throw new CitrusRuntimeException("Invalid SQL query - please use proper 'SELECT' statement");100 }101 }102 @Given("^SQL query$")103 public void addQueryStatementMultiline(String statement) {104 addQueryStatement(statement);105 }106 @Given("^SQL query statements:$")107 public void addQueryStatements(DataTable statements) {108 statements.asList().forEach(this::addQueryStatement);109 }110 @Then("^verify column ([^\"\\s]+)=(.+)$")111 public void verifyColumn(String name, String value) {112 if (maxRetryAttempts > 0) {113 runner.run(repeatOnError()114 .until((index, context) -> index >= maxRetryAttempts)115 .autoSleep(delayBetweenAttempts)116 .actions(query(dataSource)117 .statements(sqlQueryStatements)118 .validate(name, value)));119 } else {120 runner.run(query(dataSource)121 .statements(sqlQueryStatements)122 .validate(name, value));123 }124 sqlQueryStatements.clear();125 }126 @Then("^verify columns$")127 public void verifyResultSet(DataTable expectedResults) {128 ExecuteSQLQueryAction.Builder action = query(dataSource)129 .statements(sqlQueryStatements);130 List<List<String>> rows = expectedResults.asLists(String.class);131 rows.forEach(row -> {132 if (!row.isEmpty()) {133 String columnName = row.remove(0);134 action.validate(columnName, row.toArray(new String[]{}));135 }136 });137 if (maxRetryAttempts > 0) {138 runner.run(repeatOnError()139 .until((index, context) -> index >= maxRetryAttempts)140 .autoSleep(delayBetweenAttempts)141 .actions(action));142 } else {...
Source:Actions.java
...22import com.consol.citrus.actions.CreateVariablesAction;23import com.consol.citrus.actions.EchoAction;24import com.consol.citrus.actions.ExecutePLSQLAction;25import com.consol.citrus.actions.ExecuteSQLAction;26import com.consol.citrus.actions.ExecuteSQLQueryAction;27import com.consol.citrus.actions.FailAction;28import com.consol.citrus.actions.ReceiveMessageAction;29import com.consol.citrus.actions.SendMessageAction;30import com.consol.citrus.actions.SleepAction;31import com.consol.citrus.container.FinallySequence;32import com.consol.citrus.container.Iterate;33import com.consol.citrus.container.Parallel;34import com.consol.citrus.container.RepeatOnErrorUntilTrue;35import com.consol.citrus.container.RepeatUntilTrue;36import com.consol.citrus.container.Sequence;37import com.consol.citrus.container.Timer;38import groovy.lang.GroovyRuntimeException;39import org.springframework.util.ReflectionUtils;40/**41 * Set of supported test actions that can be used in a Groovy shell script.42 * @author Christoph Deppisch43 */44public enum Actions {45 ECHO("echo", EchoAction.Builder.class),46 SLEEP("sleep", SleepAction.Builder.class),47 SQL("sql", ExecuteSQLAction.Builder.class),48 PLSQL("plsql", ExecutePLSQLAction.Builder.class),49 QUERY("query", ExecuteSQLQueryAction.Builder.class),50 CREATE_VARIABLE("createVariable", CreateVariablesAction.Builder.class),51 CREATE_VARIABLES("createVariables", CreateVariablesAction.Builder.class),52 SEND("send",SendMessageAction.Builder.class),53 RECEIVE("receive", ReceiveMessageAction.Builder.class),54 FAIL("fail", FailAction.Builder.class),55 SEQUENCE("sequence", Sequence.Builder.class),56 ITERATE("iterate", Iterate.Builder.class),57 PARALLEL("parallel", Parallel.Builder.class),58 REPEAT("repeat", RepeatUntilTrue.Builder.class),59 REPEAT_ON_ERROR("repeatOnError", RepeatOnErrorUntilTrue.Builder.class),60 TIMER("timer", Timer.Builder.class),61 DO_FINALLY("doFinally", FinallySequence.Builder.class);62 private final String id;63 private final Class<? extends TestActionBuilder<?>> builderType;...
Source:ItemTest.java
...7import org.springframework.beans.factory.annotation.Autowired;8import org.springframework.http.HttpStatus;9import org.testng.annotations.Test;10import static com.consol.citrus.actions.ExecuteSQLAction.Builder.sql;11import static com.consol.citrus.actions.ExecuteSQLQueryAction.Builder.query;12import static com.consol.citrus.http.actions.HttpActionBuilder.http;13import static com.consol.citrus.validation.json.JsonPathMessageValidationContext.Builder.jsonPath;14@Test15public class ItemTest extends TestNGCitrusSpringSupport {16 @Autowired17 private HttpClient secondHandApiEndpoint;18 @Autowired19 private BasicDataSource secondHandApiDataSource;20 @CitrusTest21 public void getOneItem() {22 description("WENN ein Item in der Datenbank vorhanden ist " +23 "UND alle Items abegrufen werden " +24 "DANN sollte die API ein JSON mit einem Item herausgeben");25 $(sql(secondHandApiDataSource)...
ExecuteSQLQueryAction
Using AI Code Generation
1package com.consol.citrus.samples;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.junit.JUnit4CitrusTestDesigner;4import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;5import org.testng.annotations.Test;6public class 4 extends TestNGCitrusTestDesigner {7public void 4() {8description("Execute SQL query");9sql(query("SELECT * FROM BOOKS"));10}11}12package com.consol.citrus.samples;13import com.consol.citrus.annotations.CitrusTest;14import com.consol.citrus.dsl.junit.JUnit4CitrusTestDesigner;15import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;16import org.testng.annotations.Test;17public class 5 extends TestNGCitrusTestDesigner {18public void 5() {19description("Execute SQL query");20sql(query("SELECT * FROM BOOKS"));21}22}23package com.consol.citrus.samples;24import com.consol.citrus.annotations.CitrusTest;25import com.consol.citrus.dsl.junit.JUnit4CitrusTestDesigner;26import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;27import org.testng.annotations.Test;28public class 6 extends TestNGCitrusTestDesigner {29public void 6() {30description("Execute SQL query");31sql(query("SELECT * FROM BOOKS"));32}33}34package com.consol.citrus.samples;35import com.consol.citrus.annotations.CitrusTest;36import com.consol.citrus.dsl.junit.JUnit4CitrusTestDesigner;37import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;38import org.testng.annotations.Test;39public class 7 extends TestNGCitrusTestDesigner {40public void 7() {41description("Execute SQL query");42sql(query("SELECT * FROM BOOKS"));43}44}
ExecuteSQLQueryAction
Using AI Code Generation
1package com.consol.citrus.samples;2import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;3import com.consol.citrus.jdbc.actions.ExecuteSQLQueryAction;4import org.springframework.beans.factory.annotation.Autowired;5import org.springframework.jdbc.datasource.DriverManagerDataSource;6import org.testng.annotations.Test;7public class ExecuteSQLQueryActionJavaIT extends TestNGCitrusTestDesigner {8 private DriverManagerDataSource dataSource;9 public void executeSQLQueryActionJavaIT() {
ExecuteSQLQueryAction
Using AI Code Generation
1public class 4 extends TestNGCitrusTestDesigner {2 public void configure() {3 executeSQLQuery()4 .dataSource(dataSource)5 .statement("SELECT * FROM CUSTOMER WHERE ID = ?")6 .parameter(1)7 .validate("ID", "1")8 .validate("NAME", "John Doe")9 .validate("EMAIL", "
ExecuteSQLQueryAction
Using AI Code Generation
1ExecuteSQLQueryAction queryAction = new ExecuteSQLQueryAction();2queryAction.setDataSource(dataSource);3queryAction.setSqlQuery("select * from CUSTOMER");4queryAction.setVariable("customer");5queryAction.setRowMapper(new RowMapper<Customer>() {6public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {7Customer customer = new Customer();8customer.setId(rs.getString("ID"));9customer.setFirstName(rs.getString("FIRST_NAME"));10customer.setLastName(rs.getString("LAST_NAME"));11return customer;12}13});14queryAction.execute(context);15List<Customer> customerList = context.getVariable("customer");16System.out.println(customerList);17ExecuteSQLUpdateAction updateAction = new ExecuteSQLUpdateAction();18updateAction.setDataSource(dataSource);19updateAction.setSqlQuery("update CUSTOMER set FIRST_NAME = 'John'");20updateAction.execute(context);21ExecuteSQLScriptAction scriptAction = new ExecuteSQLScriptAction();22scriptAction.setDataSource(dataSource);23scriptAction.setSqlResource(new ClassPathResource("sql/customer.sql"));24scriptAction.execute(context);25ExecuteSQLStoredProcAction procAction = new ExecuteSQLStoredProcAction();26procAction.setDataSource(dataSource);27procAction.setSqlResource(new ClassPathResource("sql/customer.sql"));28procAction.setCallableStatement("{call CUSTOMER_PROC(?, ?, ?)}");29procAction.setVariable("customer");30procAction.setRowMapper(new RowMapper<Customer>() {31public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {32Customer customer = new Customer();33customer.setId(rs.getString("ID"));34customer.setFirstName(rs.getString("FIRST_NAME"));35customer.setLastName(rs.getString("LAST_NAME"));36return customer;37}38});39procAction.execute(context);40List<Customer> customerList = context.getVariable("customer");41System.out.println(customerList);42ExecuteSQLQueryAction queryAction = new ExecuteSQLQueryAction();43queryAction.setDataSource(dataSource);44queryAction.setSqlQuery("select * from CUSTOMER");45queryAction.setVariable("customer
ExecuteSQLQueryAction
Using AI Code Generation
1package com.consol.citrus;2import org.testng.annotations.Test;3public class ExecuteSQLQueryActionTest extends TestNGCitrusTestDesigner {4public void testExecuteSQLQueryAction() {5executeSQLQueryAction()6.database("jdbc:derby:memory:myDB;create=true")7.query("CREATE TABLE MYTABLE (ID INTEGER, NAME VARCHAR(50))")8.query("INSERT INTO MYTABLE VALUES (1, 'Citrus')")9.query("INSERT INTO MYTABLE VALUES (2, 'Citrus Framework')")10.query("SELECT * FROM MYTABLE")11.validate("ID", "1")12.validate("NAME", "Citrus")13.validate("ID", "2")14.validate("NAME", "Citrus Framework");15}16}17executeSQLUpdateAction()18.database("jdbc:derby:memory:myDB;create=true")19.query("CREATE TABLE MYTABLE (ID INTEGER, NAME VARCHAR(50))")20.query("INSERT INTO MYTABLE VALUES (1, 'Citrus')")21.query("INSERT
ExecuteSQLQueryAction
Using AI Code Generation
1package com.consol.citrus.dsl.testng;2import com.consol.citrus.Citrus;3import com.consol.citrus.actions.ExecuteSQLQueryAction;4import com.consol.citrus.context.TestContextFactory;5import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;6import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;7import com.consol.citrus.exceptions.CitrusRuntimeException;8import com.consol.citrus.testng.AbstractTestNGUnitTest;9import org.springframework.jdbc.core.JdbcTemplate;10import org.springframework.jdbc.datasource.DriverManagerDataSource;11import org.testng.annotations.Test;12public class 4 extends AbstractTestNGUnitTest {13 public void testExecuteSQLQueryAction() {14 DriverManagerDataSource dataSource = new DriverManagerDataSource();15 dataSource.setDriverClassName("org.hsqldb.jdbcDriver");16 dataSource.setUrl("jdbc:hsqldb:mem:testdb");17 dataSource.setUsername("sa");18 dataSource.setPassword("");19 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);20 jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS CITRUS_TEST (ID INTEGER, NAME VARCHAR(255))");21 jdbcTemplate.execute("INSERT INTO CITRUS_TEST VALUES (1, 'Hello')");22 jdbcTemplate.execute("INSERT INTO CITRUS_TEST VALUES (2, 'World')");23 TestNGCitrusTestRunner runner = new TestNGCitrusTestRunner(this, context) {24 public void execute() {25 executeSQLQueryAction(new ExecuteSQLQueryAction.Builder()26 .dataSource(dataSource)27 .sqlQuery("SELECT * FROM CITRUS_TEST")28 .variable("result", "citrus:sqlQueryResult()")29 .build());30 }31 };32 runner.run();33 runner.assertVariable("result", Citrus.resolve("${citrus:sqlQueryResult()}"));34 }35 public void testExecuteSQLQueryActionWithResultMapping() {36 DriverManagerDataSource dataSource = new DriverManagerDataSource();37 dataSource.setDriverClassName("org.hsqldb.jdbcDriver");38 dataSource.setUrl("jdbc:hsqldb:mem:testdb");39 dataSource.setUsername("sa");40 dataSource.setPassword("");41 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);42 jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS CITRUS_TEST (ID INTEGER, NAME
ExecuteSQLQueryAction
Using AI Code Generation
1public class 4 extends TestCase {2 public void 4() {3 variable("result", "select * from emp where name='John'");4 executeSQLQueryAction(5 sqlQuery("select * from emp where name='John'"),6 sqlUsername("postgres"),7 sqlPassword("postgres"),8 sqlDriver("org.postgresql.Driver"),9 sqlValidateQueryResult("${result}")10 );11 }12}13public class 5 extends TestCase {14 public void 5() {15 variable("result", "select * from emp where name='John'");16 executeSQLQueryAction(17 sqlQuery("select * from emp where name='John'"),18 sqlUsername("postgres"),19 sqlPassword("postgres"),20 sqlDriver("org.postgresql.Driver"),21 sqlValidateQueryResult("${result}")22 );23 }24}25public class 6 extends TestCase {26 public void 6() {27 variable("result", "select * from emp where name='John'");28 executeSQLQueryAction(29 sqlQuery("select * from emp where name='John'"),30 sqlUsername("postgres"),31 sqlPassword("postgres"),32 sqlDriver("org.postgresql.Driver"),33 sqlValidateQueryResult("${result}")34 );35 }36}37public class 7 extends TestCase {38 public void 7() {39 variable("result", "select * from emp where name='John'");40 executeSQLQueryAction(41 sqlQuery("select * from emp where name='
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!