Best Citrus code snippet using com.consol.citrus.testng.AbstractTestNGCitrusTest.prepareTestContext
Source:AbstractTestNGCitrusTest.java
...88 protected void run(ITestResult testResult, Method method, TestLoader testLoader, int invocationCount) {89 if (citrus == null) {90 citrus = Citrus.newInstance(applicationContext);91 }92 TestContext ctx = prepareTestContext(citrus.createTestContext());93 TestCase testCase = testLoader.load();94 testCase.setGroups(testResult.getMethod().getGroups());95 invokeTestMethod(testResult, method, testCase, ctx, invocationCount);96 }97 /**98 * Invokes test method based on designer or runner environment.99 * @param testResult100 * @param method101 * @param testCase102 * @param context103 * @param invocationCount104 */105 protected void invokeTestMethod(ITestResult testResult, Method method, TestCase testCase, TestContext context, int invocationCount) {106 try {107 ReflectionUtils.invokeMethod(method, this,108 resolveParameter(testResult, method, testCase, context, invocationCount));109 citrus.run(testCase, context);110 } catch (TestCaseFailedException e) {111 throw e;112 } catch (Exception | AssertionError e) {113 testCase.setTestResult(TestResult.failed(testCase.getName(), testCase.getTestClass().getName(), e));114 testCase.finish(context);115 throw new TestCaseFailedException(e);116 }117 }118 /**119 * Resolves method arguments supporting TestNG data provider parameters as well as120 * {@link CitrusResource} annotated methods.121 *122 * @param testResult123 * @param method124 * @param testCase125 * @param context126 * @param invocationCount127 * @return128 */129 protected Object[] resolveParameter(ITestResult testResult, final Method method, TestCase testCase, TestContext context, int invocationCount) {130 Object[] dataProviderParams = null;131 if (method.getAnnotation(Test.class) != null &&132 StringUtils.hasText(method.getAnnotation(Test.class).dataProvider())) {133 final Method[] dataProvider = new Method[1];134 ReflectionUtils.doWithMethods(method.getDeclaringClass(), current -> {135 if (StringUtils.hasText(current.getAnnotation(DataProvider.class).name()) &&136 current.getAnnotation(DataProvider.class).name().equals(method.getAnnotation(Test.class).dataProvider())) {137 dataProvider[0] = current;138 } else if (current.getName().equals(method.getAnnotation(Test.class).dataProvider())) {139 dataProvider[0] = current;140 }141 }, toFilter -> toFilter.getAnnotation(DataProvider.class) != null);142 if (dataProvider[0] == null) {143 throw new CitrusRuntimeException("Unable to find data provider: " + method.getAnnotation(Test.class).dataProvider());144 }145 Object[][] parameters = (Object[][]) ReflectionUtils.invokeMethod(dataProvider[0], this,146 resolveParameter(testResult, dataProvider[0], testCase, context, -1));147 if (parameters != null) {148 dataProviderParams = parameters[invocationCount % parameters.length];149 injectTestParameters(method, testCase, dataProviderParams);150 }151 }152 Object[] values = new Object[method.getParameterTypes().length];153 Class<?>[] parameterTypes = method.getParameterTypes();154 for (int i = 0; i < parameterTypes.length; i++) {155 final Annotation[] parameterAnnotations = method.getParameterAnnotations()[i];156 Class<?> parameterType = parameterTypes[i];157 for (Annotation annotation : parameterAnnotations) {158 if (annotation instanceof CitrusResource) {159 values[i] = resolveAnnotatedResource(testResult, parameterType, context);160 }161 }162 if (parameterType.equals(ITestResult.class)) {163 values[i] = testResult;164 } else if (parameterType.equals(ITestContext.class)) {165 values[i] = testResult.getTestContext();166 } else if (values[i] == null && dataProviderParams != null && i < dataProviderParams.length) {167 values[i] = dataProviderParams[i];168 }169 }170 return values;171 }172 /**173 * Resolves value for annotated method parameter.174 *175 * @param testResult176 * @param parameterType177 * @return178 */179 protected Object resolveAnnotatedResource(ITestResult testResult, Class<?> parameterType, TestContext context) {180 if (TestContext.class.isAssignableFrom(parameterType)) {181 return context;182 } else {183 throw new CitrusRuntimeException("Not able to provide a Citrus resource injection for type " + parameterType);184 }185 }186 /**187 * Creates test loader from @CitrusXmlTest annotated test method and saves those to local member.188 * Test loaders get executed later when actual method is called by TestNG. This way user can annotate189 * multiple methods in one single class each executing several Citrus XML tests.190 *191 * @param method192 * @return193 */194 private List<TestLoader> createTestLoadersForMethod(Method method) {195 List<TestLoader> methodTestLoaders = new ArrayList<TestLoader>();196 if (method.getAnnotation(CitrusXmlTest.class) != null) {197 CitrusXmlTest citrusTestAnnotation = method.getAnnotation(CitrusXmlTest.class);198 String[] testNames = new String[] {};199 if (citrusTestAnnotation.name().length > 0) {200 testNames = citrusTestAnnotation.name();201 } else if (citrusTestAnnotation.packageScan().length == 0) {202 // only use default method name as test in case no package scan is set203 testNames = new String[] { method.getName() };204 }205 String testPackage;206 if (StringUtils.hasText(citrusTestAnnotation.packageName())) {207 testPackage = citrusTestAnnotation.packageName();208 } else {209 testPackage = method.getDeclaringClass().getPackage().getName();210 }211 for (String testName : testNames) {212 methodTestLoaders.add(createTestLoader(testName, testPackage));213 }214 String[] packagesToScan = citrusTestAnnotation.packageScan();215 for (String packageScan : packagesToScan) {216 try {217 for (String fileNamePattern : Citrus.getXmlTestFileNamePattern()) {218 Resource[] fileResources = new PathMatchingResourcePatternResolver().getResources(packageScan.replace('.', File.separatorChar) + fileNamePattern);219 for (Resource fileResource : fileResources) {220 String filePath = fileResource.getFile().getParentFile().getCanonicalPath();221 if (packageScan.startsWith("file:")) {222 filePath = "file:" + filePath;223 }224 225 filePath = filePath.substring(filePath.indexOf(packageScan.replace('.', File.separatorChar)));226 methodTestLoaders.add(createTestLoader(fileResource.getFilename().substring(0, fileResource.getFilename().length() - ".xml".length()), filePath));227 }228 }229 } catch (RuntimeException | IOException e) {230 throw new CitrusRuntimeException("Unable to locate file resources for test package '" + packageScan + "'", e);231 }232 }233 }234 return methodTestLoaders;235 }236 /**237 * Runs tasks before test suite.238 * @param testContext the test context.239 * @throws Exception on error.240 */241 @BeforeSuite(alwaysRun = true)242 public void beforeSuite(ITestContext testContext) throws Exception {243 springTestContextPrepareTestInstance();244 Assert.notNull(applicationContext);245 citrus = Citrus.newInstance(applicationContext);246 citrus.beforeSuite(testContext.getSuite().getName(), testContext.getIncludedGroups());247 }248 /**249 * Runs tasks after test suite.250 * @param testContext the test context.251 */252 @AfterSuite(alwaysRun = true)253 public void afterSuite(ITestContext testContext) {254 if (citrus != null) {255 citrus.afterSuite(testContext.getSuite().getName(), testContext.getIncludedGroups());256 }257 }258 /**259 * Executes the test case.260 * @deprecated in favor of using {@link com.consol.citrus.annotations.CitrusXmlTest} or {@link com.consol.citrus.annotations.CitrusTest} annotations on test methods.261 */262 @Deprecated263 protected void executeTest() {264 if (citrus == null) {265 citrus = Citrus.newInstance(applicationContext);266 }267 ITestResult result = Reporter.getCurrentTestResult();268 ITestNGMethod testNGMethod = result.getMethod();269 TestContext context = prepareTestContext(citrus.createTestContext());270 TestLoader testLoader = createTestLoader(this.getClass().getSimpleName(), this.getClass().getPackage().getName());271 TestCase testCase = testLoader.load();272 testCase.setGroups(testNGMethod.getGroups());273 resolveParameter(result, testNGMethod.getConstructorOrMethod().getMethod(), testCase, context, testNGMethod.getCurrentInvocationCount());274 citrus.run(testCase, context);275 }276 /**277 * Prepares the test context.278 *279 * Provides a hook for test context modifications before the test gets executed.280 *281 * @param testContext the test context.282 * @return the (prepared) test context.283 */284 protected TestContext prepareTestContext(final TestContext testContext) {285 return testContext;286 }287 /**288 * Creates new test loader which has TestNG test annotations set for test execution. Only289 * suitable for tests that get created at runtime through factory method. Subclasses290 * may overwrite this in order to provide custom test loader with custom test annotations set.291 * @param testName292 * @param packageName293 * @return294 */295 protected TestLoader createTestLoader(String testName, String packageName) {296 return new XmlTestLoader(getClass(), testName, packageName, applicationContext);297 }298 /**...
Source:TestNGCitrusTest.java
...75 try {76 if (citrus == null) {77 citrus = Citrus.newInstance(applicationContext);78 }79 TestContext ctx = prepareTestContext(citrus.createTestContext());80 if (isDesignerMethod(method)) {81 testDesigner = createTestDesigner(method, ctx);82 } else if (isRunnerMethod(method)) {83 testRunner = createTestRunner(method, ctx);84 } else {85 throw new CitrusRuntimeException("Missing designer or runner method parameter");86 }87 testResult.setAttribute(DESIGNER_ATTRIBUTE, testDesigner);88 testResult.setAttribute(RUNNER_ATTRIBUTE, testRunner);89 TestCase testCase = testDesigner != null ? testDesigner.getTestCase() : testRunner.getTestCase();90 testCase.setGroups(testResult.getMethod().getGroups());91 CitrusAnnotations.injectAll(this, citrus, ctx);92 invokeTestMethod(testResult, method, testCase, ctx, invocationCount);93 } finally {...
prepareTestContext
Using AI Code Generation
1package com.consol.citrus;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.annotations.CitrusXmlTest;4import com.consol.citrus.testng.AbstractTestNGCitrusTest;5import org.testng.annotations.Test;6public class 4 extends AbstractTestNGCitrusTest {7 public void test() {8 TestContext context = prepareTestContext();9 context.setVariable("var1", "test");10 echo("variable value is: ${var1}");11 }12}13package com.consol.citrus;14import com.consol.citrus.annotations.CitrusTest;15import com.consol.citrus.annotations.CitrusXmlTest;16import com.consol.citrus.testng.AbstractTestNGCitrusTest;17import org.testng.annotations.Test;18public class 5 extends AbstractTestNGCitrusTest {19 public void test() {20 TestContext context = prepareTestContext();21 context.setVariable("var1", "test");22 echo("variable value is: ${var1}");23 }24}25package com.consol.citrus;26import com.consol.citrus.annotations.CitrusTest;27import com.consol.citrus.annotations.CitrusXmlTest;28import com.consol.citrus.testng.AbstractTestNGCitrusTest;29import org.testng.annotations.Test;30public class 6 extends AbstractTestNGCitrusTest {31 public void test() {32 TestContext context = prepareTestContext();33 context.setVariable("var1", "test");
prepareTestContext
Using AI Code Generation
1public class 4 extends AbstractTestNGCitrusTest {2 public void test() {3 run(prepareTestContext());4 }5 public void prepare() {6 }7}8public class 5 extends AbstractTestNGCitrusTest {9 public void test() {10 run(prepareTestContext());11 }12 public void prepare() {13 }14}15public class 6 extends AbstractTestNGCitrusTest {16 public void test() {17 run(prepareTestContext());18 }19 public void prepare() {20 }21}22public class 7 extends AbstractTestNGCitrusTest {23 public void test() {24 run(prepareTestContext());25 }26 public void prepare() {27 }28}29public class 8 extends AbstractTestNGCitrusTest {30 public void test() {31 run(prepareTestContext());32 }33 public void prepare() {34 }35}36public class 9 extends AbstractTestNGCitrusTest {37 public void test() {38 run(prepareTestContext());39 }40 public void prepare() {41 }42}43public class 10 extends AbstractTestNGCitrusTest {
prepareTestContext
Using AI Code Generation
1public class TestNGCitrusTest extends AbstractTestNGCitrusTest {2 public void test() {3 TestContext testContext = prepareTestContext();4 testContext.setVariable("var1", "test");5 System.out.println("value of var1 is "+testContext.getVariable("var1"));6 }7}
prepareTestContext
Using AI Code Generation
1public class 4 extends AbstractTestNGCitrusTest {2 public void myFirstTest() {3 variable("firstname", "John");4 variable("lastname", "Doe");5 variable("age", "42");6 echo("Hello Citrus!");7 http()8 .client("httpClient")9 .send()10 .post()11 .fork(true)12 .payload("<person id=\"123\">" +13 "<firstname>${firstname}</firstname>" +14 "<lastname>${lastname}</lastname>" +15 "<age>${age}</age>" +16 "</person>");17 http()18 .client("httpClient")19 .receive()20 .response(HttpStatus.OK)21 .messageType(MessageType.PLAINTEXT)22 .payload("Hello ${firstname} ${lastname}! You are ${age} years old.");23 sleep(1000L);24 }25}26public class 5 extends AbstractTestNGCitrusTest {27 public void myFirstTest() {28 variable("firstname", "John");29 variable("lastname", "Doe");30 variable("age", "42");31 echo("Hello Citrus!");32 http()33 .client("httpClient")34 .send()35 .post()36 .fork(true)37 .payload("<person id=\"123\">" +38 "<firstname>${firstname}</firstname>" +39 "<lastname>${lastname}</lastname>" +40 "<age>${age}</age>" +41 "</person>");42 http()43 .client("httpClient")44 .receive()45 .response(HttpStatus.OK)46 .messageType(MessageType.PLAINTEXT)47 .payload("Hello ${firstname} ${lastname}! You are ${age} years old.");48 sleep(1000L);49 }50}51public class 6 extends AbstractTestNGCitrusTest {
prepareTestContext
Using AI Code Generation
1public void test4() {2 prepareTestContext();3 context.setVariable("name", "Citrus");4 echo("${name}");5}6public void test5() {7 prepareTestContext();8 context.setVariable("name", "Citrus");9 echo("${name}");10}11public void test6() {12 prepareTestContext();13 context.setVariable("name", "Citrus");14 echo("${name}");15}16public void test7() {17 prepareTestContext();18 context.setVariable("name", "Citrus");19 echo("${name}");20}21public void test8() {22 prepareTestContext();23 context.setVariable("name", "Citrus");24 echo("${name}");25}26public void test9() {27 prepareTestContext();28 context.setVariable("name", "Citrus");29 echo("${name}");30}31public void test10() {32 prepareTestContext();33 context.setVariable("name", "Citrus");34 echo("${name}");35}36public void test11() {37 prepareTestContext();38 context.setVariable("name", "Citrus
prepareTestContext
Using AI Code Generation
1public void testPrepareTestContext() {2 prepareTestContext().variable("testVar", "testValue");3 run(new TestActionBuilder() {4 public void build() {5 echo("testVar: ${testVar}");6 }7 });8}9public void testPrepareTestContext() {10 prepareTestContext().variable("testVar", "testValue");11 run(new TestActionBuilder() {12 public void build() {13 echo("testVar: ${testVar}");14 }15 });16}17public void testPrepareTestContext() {18 prepareTestContext().variable("testVar", "testValue");19 run(new TestActionBuilder() {20 public void build() {21 echo("testVar: ${testVar}");22 }23 });24}25public void testPrepareTestContext() {26 prepareTestContext().variable("testVar", "testValue");27 run(new TestActionBuilder() {28 public void build() {29 echo("testVar: ${testVar}");30 }31 });32}33public void testPrepareTestContext() {34 prepareTestContext().variable("testVar", "testValue");35 run(new TestActionBuilder() {
prepareTestContext
Using AI Code Generation
1public void test() {2 Assertions.assertThat(true).isTrue();3}4public void test() {5 Assertions.assertThat(true).isTrue();6}7public void test() {8 Assertions.assertThat(true).isTrue();9}10public void test() {11 Assertions.assertThat(true).isTrue();12}13public void test() {14 Assertions.assertThat(true).isTrue();15}16public void test() {17 Assertions.assertThat(true).isTrue();18}19public void test() {20 Assertions.assertThat(true).isTrue();21}22public void test() {
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!!