or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations.mdassertions.mdcollections-utilities.mdindex.mdlisteners-hooks.mdtest-execution.mdxml-configuration.md

collections-utilities.mddocs/

0

# Collections and Utilities

1

2

TestNG provides a comprehensive set of utility classes for collections, string manipulation, reflection operations, and test reporting. These utilities simplify common operations and provide consistent APIs across the framework.

3

4

## Capabilities

5

6

### Collection Factory Classes

7

8

Utility classes providing factory methods for creating various collection types with convenient APIs.

9

10

```java { .api }

11

/**

12

* Factory methods for List creation and manipulation

13

*/

14

public class Lists {

15

16

// List creation

17

public static <T> List<T> newArrayList();

18

public static <T> List<T> newArrayList(T... elements);

19

public static <T> List<T> newArrayList(Iterable<? extends T> elements);

20

public static <T> List<T> newArrayList(Iterator<? extends T> elements);

21

public static <T> List<T> newLinkedList();

22

public static <T> List<T> newLinkedList(Iterable<? extends T> elements);

23

24

// List operations

25

public static <T> List<T> intersection(List<T> list1, List<T> list2);

26

public static <T> List<T> merge(Object[] suiteResult, Object[] methodResult);

27

public static <T> List<T> createEmpyList();

28

public static boolean hasElements(Collection<?> c);

29

}

30

31

/**

32

* Factory methods for Map creation and manipulation

33

*/

34

public class Maps {

35

36

// Map creation

37

public static <K, V> Map<K, V> newHashMap();

38

public static <K, V> Map<K, V> newHashMap(Map<? extends K, ? extends V> map);

39

public static <K, V> Map<K, V> newLinkedHashMap();

40

public static <K, V> ConcurrentMap<K, V> newConcurrentMap();

41

42

// MultiMap creation

43

public static <K, V> ListMultiMap<K, V> newListMultiMap();

44

public static <K, V> ListMultiMap<K, V> newListMultiMap(Map<K, Collection<V>> map);

45

public static <K, V> SetMultiMap<K, V> newSetMultiMap();

46

public static <K, V> SetMultiMap<K, V> newSetMultiMap(Map<K, Collection<V>> map);

47

48

// Map operations

49

public static boolean hasElements(Map<?, ?> m);

50

}

51

52

/**

53

* Factory methods for Set creation

54

*/

55

public class Sets {

56

57

// Set creation

58

public static <T> Set<T> newHashSet();

59

public static <T> Set<T> newHashSet(T... elements);

60

public static <T> Set<T> newHashSet(Iterable<? extends T> elements);

61

public static <T> Set<T> newLinkedHashSet();

62

public static <T> Set<T> newLinkedHashSet(Iterable<? extends T> elements);

63

64

// Set operations

65

public static boolean hasElements(Collection<?> c);

66

}

67

```

68

69

**Usage Examples:**

70

71

```java

72

import org.testng.collections.Lists;

73

import org.testng.collections.Maps;

74

import org.testng.collections.Sets;

75

76

public class CollectionUtilityExamples {

77

78

public void demonstrateListOperations() {

79

// Create lists

80

List<String> list1 = Lists.newArrayList("a", "b", "c");

81

List<String> list2 = Lists.newArrayList("b", "c", "d");

82

List<Integer> numbers = Lists.newLinkedList();

83

84

// List operations

85

List<String> commonElements = Lists.intersection(list1, list2);

86

System.out.println("Common elements: " + commonElements); // [b, c]

87

88

// Check if list has elements

89

boolean hasElements = Lists.hasElements(list1);

90

System.out.println("List has elements: " + hasElements); // true

91

92

// Create from iterable

93

Set<String> sourceSet = Sets.newHashSet("x", "y", "z");

94

List<String> fromSet = Lists.newArrayList(sourceSet);

95

System.out.println("From set: " + fromSet);

96

}

97

98

public void demonstrateMapOperations() {

99

// Create maps

100

Map<String, Integer> map1 = Maps.newHashMap();

101

map1.put("one", 1);

102

map1.put("two", 2);

103

104

Map<String, Integer> map2 = Maps.newLinkedHashMap(map1);

105

Map<String, Integer> concurrentMap = Maps.newConcurrentMap();

106

107

// Check if map has elements

108

boolean hasElements = Maps.hasElements(map1);

109

System.out.println("Map has elements: " + hasElements); // true

110

111

// Create MultiMaps

112

ListMultiMap<String, String> listMultiMap = Maps.newListMultiMap();

113

listMultiMap.put("colors", "red");

114

listMultiMap.put("colors", "blue");

115

listMultiMap.put("colors", "green");

116

117

SetMultiMap<String, String> setMultiMap = Maps.newSetMultiMap();

118

setMultiMap.put("categories", "unit");

119

setMultiMap.put("categories", "integration");

120

setMultiMap.put("categories", "unit"); // Duplicate - will be ignored in set

121

122

System.out.println("Colors: " + listMultiMap.get("colors"));

123

System.out.println("Categories: " + setMultiMap.get("categories"));

124

}

125

126

public void demonstrateSetOperations() {

127

// Create sets

128

Set<String> set1 = Sets.newHashSet("a", "b", "c");

129

Set<Integer> set2 = Sets.newLinkedHashSet();

130

131

// Create from array

132

String[] array = {"x", "y", "z", "x"}; // Duplicate 'x'

133

Set<String> uniqueSet = Sets.newHashSet(array);

134

System.out.println("Unique elements: " + uniqueSet); // [x, y, z]

135

136

// Create from iterable

137

List<String> sourceList = Lists.newArrayList("p", "q", "r", "p");

138

Set<String> fromList = Sets.newLinkedHashSet(sourceList);

139

System.out.println("Unique from list: " + fromList); // [p, q, r] - preserves order

140

141

// Check if set has elements

142

boolean hasElements = Sets.hasElements(set1);

143

System.out.println("Set has elements: " + hasElements); // true

144

}

145

}

146

```

147

148

### MultiMap Interfaces

149

150

Multi-value map implementations that can store multiple values per key.

151

152

```java { .api }

153

/**

154

* Interface for maps that can hold multiple values per key

155

*/

156

public interface MultiMap<K, V> {

157

158

// Basic operations

159

void put(K key, V value);

160

void putAll(K key, Collection<V> values);

161

Collection<V> get(K key);

162

Collection<V> remove(K key);

163

boolean remove(K key, V value);

164

165

// Query operations

166

boolean containsKey(K key);

167

boolean containsValue(V value);

168

boolean containsEntry(K key, V value);

169

boolean isEmpty();

170

int size();

171

172

// Bulk operations

173

void clear();

174

Set<K> keySet();

175

Collection<Collection<V>> values();

176

Set<Map.Entry<K, Collection<V>>> entrySet();

177

178

// View operations

179

Map<K, Collection<V>> asMap();

180

}

181

182

/**

183

* MultiMap implementation using Lists for value storage

184

*/

185

public class ListMultiMap<K, V> implements MultiMap<K, V> {

186

187

public ListMultiMap();

188

public ListMultiMap(Map<K, Collection<V>> map);

189

190

// Inherited from MultiMap interface

191

// Additional List-specific behavior: preserves insertion order and allows duplicates

192

}

193

194

/**

195

* MultiMap implementation using Sets for value storage

196

*/

197

public class SetMultiMap<K, V> implements MultiMap<K, V> {

198

199

public SetMultiMap();

200

public SetMultiMap(Map<K, Collection<V>> map);

201

202

// Inherited from MultiMap interface

203

// Additional Set-specific behavior: no duplicate values per key

204

}

205

```

206

207

**Usage Examples:**

208

209

```java

210

public class MultiMapExamples {

211

212

public void demonstrateListMultiMap() {

213

ListMultiMap<String, String> testGroups = Maps.newListMultiMap();

214

215

// Add multiple values for same key (duplicates allowed)

216

testGroups.put("smoke", "LoginTest");

217

testGroups.put("smoke", "HomePageTest");

218

testGroups.put("smoke", "LoginTest"); // Duplicate allowed in ListMultiMap

219

220

testGroups.put("regression", "FullWorkflowTest");

221

testGroups.put("regression", "DataValidationTest");

222

223

// Retrieve values (returns List)

224

Collection<String> smokeTests = testGroups.get("smoke");

225

System.out.println("Smoke tests: " + smokeTests); // [LoginTest, HomePageTest, LoginTest]

226

227

// Check contents

228

boolean hasLoginTest = testGroups.containsEntry("smoke", "LoginTest");

229

System.out.println("Contains LoginTest in smoke: " + hasLoginTest); // true

230

231

// Get all keys

232

Set<String> groups = testGroups.keySet();

233

System.out.println("Test groups: " + groups); // [smoke, regression]

234

235

// Convert to regular map

236

Map<String, Collection<String>> asMap = testGroups.asMap();

237

System.out.println("As map: " + asMap);

238

}

239

240

public void demonstrateSetMultiMap() {

241

SetMultiMap<String, String> testCategories = Maps.newSetMultiMap();

242

243

// Add values (duplicates automatically removed)

244

testCategories.put("api", "UserServiceTest");

245

testCategories.put("api", "AuthServiceTest");

246

testCategories.put("api", "UserServiceTest"); // Duplicate - will be ignored

247

248

testCategories.put("ui", "LoginPageTest");

249

testCategories.put("ui", "DashboardTest");

250

251

// Retrieve values (returns Set)

252

Collection<String> apiTests = testCategories.get("api");

253

System.out.println("API tests: " + apiTests); // [UserServiceTest, AuthServiceTest]

254

255

// Bulk operations

256

testCategories.putAll("database",

257

Lists.newArrayList("MigrationTest", "ConnectionTest", "MigrationTest"));

258

259

Collection<String> dbTests = testCategories.get("database");

260

System.out.println("DB tests: " + dbTests); // [MigrationTest, ConnectionTest] - no duplicates

261

262

// Remove specific entry

263

boolean removed = testCategories.remove("api", "UserServiceTest");

264

System.out.println("Removed UserServiceTest: " + removed); // true

265

266

System.out.println("API tests after removal: " + testCategories.get("api"));

267

}

268

}

269

```

270

271

### String Utilities

272

273

String manipulation utilities for common operations.

274

275

```java { .api }

276

/**

277

* String manipulation utilities

278

*/

279

public class Strings {

280

281

// String validation

282

public static boolean isNullOrEmpty(String string);

283

public static boolean isNotNullAndNotEmpty(String string);

284

285

// String operations

286

public static String join(String separator, Object... objects);

287

public static String join(String separator, Iterable<?> objects);

288

public static String escapeHtml(String string);

289

public static String valueOf(Object object);

290

291

// String comparison

292

public static boolean equals(String s1, String s2);

293

public static int compare(String s1, String s2);

294

}

295

```

296

297

**Usage Examples:**

298

299

```java

300

import org.testng.util.Strings;

301

302

public class StringUtilityExamples {

303

304

public void demonstrateStringOperations() {

305

// String validation

306

String nullString = null;

307

String emptyString = "";

308

String validString = "TestNG";

309

310

System.out.println("Null or empty (null): " + Strings.isNullOrEmpty(nullString)); // true

311

System.out.println("Null or empty (empty): " + Strings.isNullOrEmpty(emptyString)); // true

312

System.out.println("Null or empty (valid): " + Strings.isNullOrEmpty(validString)); // false

313

314

System.out.println("Not null and not empty: " + Strings.isNotNullAndNotEmpty(validString)); // true

315

316

// String joining

317

String joined1 = Strings.join(", ", "apple", "banana", "cherry");

318

System.out.println("Joined with comma: " + joined1); // apple, banana, cherry

319

320

List<String> items = Lists.newArrayList("test1", "test2", "test3");

321

String joined2 = Strings.join(" | ", items);

322

System.out.println("Joined list: " + joined2); // test1 | test2 | test3

323

324

// HTML escaping

325

String htmlString = "<script>alert('test')</script>";

326

String escaped = Strings.escapeHtml(htmlString);

327

System.out.println("Escaped HTML: " + escaped); // &lt;script&gt;alert('test')&lt;/script&gt;

328

329

// Value conversion

330

Object nullObject = null;

331

Integer number = 42;

332

String nullValue = Strings.valueOf(nullObject);

333

String numberValue = Strings.valueOf(number);

334

335

System.out.println("Null value: '" + nullValue + "'"); // ''

336

System.out.println("Number value: " + numberValue); // 42

337

338

// String comparison

339

String str1 = "TestNG";

340

String str2 = "testng";

341

String str3 = "TestNG";

342

343

System.out.println("Equals (case sensitive): " + Strings.equals(str1, str3)); // true

344

System.out.println("Equals (different case): " + Strings.equals(str1, str2)); // false

345

346

int comparison = Strings.compare(str1, str2);

347

System.out.println("Comparison result: " + comparison); // negative (str1 < str2 lexicographically)

348

}

349

}

350

```

351

352

### Collection Utilities

353

354

General utilities for collection operations and validation.

355

356

```java { .api }

357

/**

358

* General collection utility methods

359

*/

360

public class CollectionUtils {

361

362

// Collection validation

363

public static boolean hasElements(Collection<?> collection);

364

public static boolean hasElements(Map<?, ?> map);

365

public static boolean hasElements(Object[] array);

366

367

// Collection operations

368

public static <T> List<T> filter(Collection<T> collection, Predicate<T> predicate);

369

public static <T, R> List<R> transform(Collection<T> collection, Function<T, R> function);

370

public static <T> T findFirst(Collection<T> collection, Predicate<T> predicate);

371

372

// Array utilities

373

public static <T> boolean arrayHasElements(T[] array);

374

public static <T> List<T> arrayToList(T[] array);

375

}

376

377

/**

378

* Object utility methods

379

*/

380

public class Objects {

381

382

// Object validation

383

public static boolean isNull(Object object);

384

public static boolean isNotNull(Object object);

385

386

// Object comparison

387

public static boolean equals(Object obj1, Object obj2);

388

public static int hashCode(Object... objects);

389

390

// String representation

391

public static String toString(Object object);

392

public static String toString(Object object, String defaultValue);

393

}

394

```

395

396

**Usage Examples:**

397

398

```java

399

public class UtilityExamples {

400

401

public void demonstrateCollectionUtils() {

402

// Collection validation

403

List<String> emptyList = Lists.newArrayList();

404

List<String> nonEmptyList = Lists.newArrayList("item1", "item2");

405

Map<String, String> emptyMap = Maps.newHashMap();

406

String[] emptyArray = new String[0];

407

String[] nonEmptyArray = {"a", "b", "c"};

408

409

System.out.println("Empty list has elements: " + CollectionUtils.hasElements(emptyList)); // false

410

System.out.println("Non-empty list has elements: " + CollectionUtils.hasElements(nonEmptyList)); // true

411

System.out.println("Empty map has elements: " + CollectionUtils.hasElements(emptyMap)); // false

412

System.out.println("Empty array has elements: " + CollectionUtils.hasElements(emptyArray)); // false

413

System.out.println("Non-empty array has elements: " + CollectionUtils.hasElements(nonEmptyArray)); // true

414

415

// Array operations

416

boolean arrayHasElements = CollectionUtils.arrayHasElements(nonEmptyArray);

417

System.out.println("Array has elements: " + arrayHasElements); // true

418

419

List<String> listFromArray = CollectionUtils.arrayToList(nonEmptyArray);

420

System.out.println("List from array: " + listFromArray); // [a, b, c]

421

}

422

423

public void demonstrateObjectUtils() {

424

// Object validation

425

Object nullObject = null;

426

Object nonNullObject = "TestNG";

427

428

System.out.println("Object is null: " + Objects.isNull(nullObject)); // true

429

System.out.println("Object is not null: " + Objects.isNotNull(nonNullObject)); // true

430

431

// Object comparison

432

String str1 = "test";

433

String str2 = "test";

434

String str3 = "different";

435

436

System.out.println("Objects equal: " + Objects.equals(str1, str2)); // true

437

System.out.println("Objects not equal: " + Objects.equals(str1, str3)); // false

438

System.out.println("Null comparison: " + Objects.equals(null, null)); // true

439

440

// Hash code generation

441

int hashCode = Objects.hashCode(str1, str2, 42);

442

System.out.println("Combined hash code: " + hashCode);

443

444

// String representation

445

String nullString = Objects.toString(nullObject);

446

String nonNullString = Objects.toString(nonNullObject);

447

String defaultString = Objects.toString(nullObject, "DEFAULT");

448

449

System.out.println("Null to string: '" + nullString + "'"); // 'null'

450

System.out.println("Non-null to string: " + nonNullString); // TestNG

451

System.out.println("Null with default: " + defaultString); // DEFAULT

452

}

453

}

454

```

455

456

### Reporter Utility

457

458

Logging and reporting utilities for test output and HTML report generation.

459

460

```java { .api }

461

/**

462

* Utility class for logging test output and generating reports

463

*/

464

public class Reporter {

465

466

// Logging methods

467

public static void log(String message);

468

public static void log(String message, boolean logToStandardOut);

469

public static void log(String message, int level);

470

public static void log(String message, int level, boolean logToStandardOut);

471

472

// Output management

473

public static List<String> getOutput();

474

public static List<String> getOutput(ITestResult result);

475

public static void clear();

476

477

// Current test result access

478

public static ITestResult getCurrentTestResult();

479

480

// HTML escaping control

481

public static void setEscapeHtml(boolean escapeHtml);

482

public static boolean getEscapeHtml();

483

}

484

```

485

486

**Usage Examples:**

487

488

```java

489

import org.testng.Reporter;

490

import org.testng.annotations.Test;

491

492

public class ReporterExamples {

493

494

@Test

495

public void demonstrateReporterLogging() {

496

// Basic logging

497

Reporter.log("Starting test execution");

498

Reporter.log("Initializing test data", true); // Also log to standard out

499

500

// Logging with levels

501

Reporter.log("Debug information", 3);

502

Reporter.log("Important message", 1, true);

503

504

// Test steps logging

505

Reporter.log("Step 1: Opening application");

506

performStep1();

507

508

Reporter.log("Step 2: User login");

509

performStep2();

510

511

Reporter.log("Step 3: Verifying dashboard");

512

performStep3();

513

514

Reporter.log("Test completed successfully");

515

}

516

517

@Test

518

public void demonstrateHtmlLogging() {

519

// HTML content in logs

520

Reporter.setEscapeHtml(false); // Allow HTML tags

521

522

Reporter.log("<h3>Test Results Summary</h3>");

523

Reporter.log("<ul>");

524

Reporter.log("<li><b>Login:</b> <span style='color:green'>PASSED</span></li>");

525

Reporter.log("<li><b>Navigation:</b> <span style='color:green'>PASSED</span></li>");

526

Reporter.log("<li><b>Data Entry:</b> <span style='color:red'>FAILED</span></li>");

527

Reporter.log("</ul>");

528

529

// Include screenshot link

530

String screenshotPath = "screenshots/test-failure.png";

531

Reporter.log("<a href='" + screenshotPath + "'>View Screenshot</a>");

532

533

Reporter.setEscapeHtml(true); // Reset to safe default

534

}

535

536

@Test

537

public void demonstrateReporterUtilities() {

538

Reporter.log("Test message 1");

539

Reporter.log("Test message 2");

540

Reporter.log("Test message 3");

541

542

// Get current test result

543

ITestResult currentResult = Reporter.getCurrentTestResult();

544

if (currentResult != null) {

545

String testName = currentResult.getMethod().getMethodName();

546

Reporter.log("Current test method: " + testName);

547

}

548

549

// Get all output for current test

550

List<String> output = Reporter.getOutput(currentResult);

551

System.out.println("Total log messages: " + output.size());

552

553

// Get all output (across all tests)

554

List<String> allOutput = Reporter.getOutput();

555

System.out.println("Total messages across all tests: " + allOutput.size());

556

}

557

558

private void performStep1() {

559

Reporter.log(" - Application opened successfully");

560

}

561

562

private void performStep2() {

563

Reporter.log(" - User credentials entered");

564

Reporter.log(" - Login button clicked");

565

Reporter.log(" - Login successful");

566

}

567

568

private void performStep3() {

569

Reporter.log(" - Dashboard loaded");

570

Reporter.log(" - User data displayed correctly");

571

Reporter.log(" - Navigation menu visible");

572

}

573

}

574

```

575

576

### Reflection Utilities

577

578

Reflection utility classes for method and class introspection.

579

580

```java { .api }

581

/**

582

* Reflection utility methods

583

*/

584

public class ReflectionHelper {

585

586

// Method introspection

587

public static List<Method> getLocalMethods(Class<?> clazz);

588

public static List<Method> excludingMain(List<Method> methods);

589

public static List<Method> getDefaultMethods(Class<?> clazz);

590

591

// Class introspection

592

public static boolean hasDefaultConstructor(Class<?> clazz);

593

public static Constructor<?> getDefaultConstructor(Class<?> clazz);

594

595

// Method filtering

596

public static List<Method> filterMethods(List<Method> methods, Predicate<Method> predicate);

597

public static boolean isTestMethod(Method method);

598

public static boolean isConfigurationMethod(Method method);

599

}

600

```

601

602

## Types

603

604

```java { .api }

605

// Functional interfaces for collection operations

606

@FunctionalInterface

607

public interface Predicate<T> {

608

boolean test(T t);

609

}

610

611

@FunctionalInterface

612

public interface Function<T, R> {

613

R apply(T t);

614

}

615

616

// Result map interface for test results

617

public interface IResultMap {

618

void addResult(ITestResult result, ITestNGMethod method);

619

Set<ITestResult> getResults(ITestNGMethod method);

620

Set<ITestResult> getAllResults();

621

void removeResult(ITestNGMethod method);

622

Collection<ITestNGMethod> getAllMethods();

623

int size();

624

}

625

626

// Common data structures

627

public class Pair<A, B> {

628

public final A first;

629

public final B second;

630

631

public Pair(A first, B second);

632

public A first();

633

public B second();

634

}

635

636

public class Triple<A, B, C> {

637

public final A first;

638

public final B second;

639

public final C third;

640

641

public Triple(A first, B second, C third);

642

public A first();

643

public B second();

644

public C third();

645

}

646

```