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

assertions.mddocs/

0

# Assertions

1

2

TestNG's assertion framework provides comprehensive static methods for test verification through the Assert class, plus advanced assertion collection capabilities with SoftAssert for scenarios requiring multiple assertion validations.

3

4

## Capabilities

5

6

### Assert Class

7

8

The main assertion class providing static methods for test verification. All assertion methods throw AssertionError on failure with detailed error messages.

9

10

```java { .api }

11

/**

12

* Main assertion class with static methods for test verification

13

*/

14

public class Assert {

15

16

// Basic boolean assertions

17

public static void assertTrue(boolean condition);

18

public static void assertTrue(boolean condition, String message);

19

public static void assertFalse(boolean condition);

20

public static void assertFalse(boolean condition, String message);

21

22

// Null/not-null assertions

23

public static void assertNull(Object object);

24

public static void assertNull(Object object, String message);

25

public static void assertNotNull(Object object);

26

public static void assertNotNull(Object object, String message);

27

28

// Equality assertions

29

public static void assertEquals(Object actual, Object expected);

30

public static void assertEquals(Object actual, Object expected, String message);

31

public static void assertEquals(String actual, String expected);

32

public static void assertEquals(String actual, String expected, String message);

33

public static void assertEquals(double actual, double expected, double delta);

34

public static void assertEquals(double actual, double expected, double delta, String message);

35

public static void assertEquals(float actual, float expected, float delta);

36

public static void assertEquals(float actual, float expected, float delta, String message);

37

38

// Inequality assertions

39

public static void assertNotEquals(Object actual, Object expected);

40

public static void assertNotEquals(Object actual, Object expected, String message);

41

public static void assertNotEquals(String actual, String expected);

42

public static void assertNotEquals(String actual, String expected, String message);

43

public static void assertNotEquals(double actual, double expected, double delta);

44

public static void assertNotEquals(double actual, double expected, double delta, String message);

45

public static void assertNotEquals(float actual, float expected, float delta);

46

public static void assertNotEquals(float actual, float expected, float delta, String message);

47

48

// Object identity assertions

49

public static void assertSame(Object actual, Object expected);

50

public static void assertSame(Object actual, Object expected, String message);

51

public static void assertNotSame(Object actual, Object expected);

52

public static void assertNotSame(Object actual, Object expected, String message);

53

54

// Array assertions

55

public static void assertEquals(Object[] actual, Object[] expected);

56

public static void assertEquals(Object[] actual, Object[] expected, String message);

57

public static void assertEquals(byte[] actual, byte[] expected);

58

public static void assertEquals(byte[] actual, byte[] expected, String message);

59

public static void assertEquals(short[] actual, short[] expected);

60

public static void assertEquals(short[] actual, short[] expected, String message);

61

public static void assertEquals(int[] actual, int[] expected);

62

public static void assertEquals(int[] actual, int[] expected, String message);

63

public static void assertEquals(long[] actual, long[] expected);

64

public static void assertEquals(long[] actual, long[] expected, String message);

65

public static void assertEquals(char[] actual, char[] expected);

66

public static void assertEquals(char[] actual, char[] expected, String message);

67

public static void assertEquals(float[] actual, float[] expected, float delta);

68

public static void assertEquals(float[] actual, float[] expected, float delta, String message);

69

public static void assertEquals(double[] actual, double[] expected, double delta);

70

public static void assertEquals(double[] actual, double[] expected, double delta, String message);

71

72

// Collection assertions

73

public static void assertEquals(Set<?> actual, Set<?> expected);

74

public static void assertEquals(Set<?> actual, Set<?> expected, String message);

75

public static void assertEquals(Map<?, ?> actual, Map<?, ?> expected);

76

public static void assertEquals(Map<?, ?> actual, Map<?, ?> expected, String message);

77

78

// Exception assertions

79

public static <T extends Throwable> T expectThrows(Class<T> expectedType, Executable executable);

80

public static <T extends Throwable> T expectThrows(Class<T> expectedType, Executable executable, String message);

81

82

// Failure methods

83

public static void fail();

84

public static void fail(String message);

85

public static void fail(String message, Throwable realCause);

86

}

87

```

88

89

**Usage Examples:**

90

91

```java

92

import org.testng.Assert;

93

import org.testng.annotations.Test;

94

95

public class AssertionExamples {

96

97

@Test

98

public void testBasicAssertions() {

99

// Boolean assertions

100

Assert.assertTrue(5 > 3, "5 should be greater than 3");

101

Assert.assertFalse(2 > 5, "2 should not be greater than 5");

102

103

// Null assertions

104

Object nullObject = null;

105

Object nonNullObject = new Object();

106

Assert.assertNull(nullObject);

107

Assert.assertNotNull(nonNullObject);

108

}

109

110

@Test

111

public void testEqualityAssertions() {

112

// Object equality

113

String expected = "Hello TestNG";

114

String actual = "Hello TestNG";

115

Assert.assertEquals(actual, expected);

116

117

// Numeric equality

118

int expectedInt = 42;

119

int actualInt = 42;

120

Assert.assertEquals(actualInt, expectedInt);

121

122

// Floating point with delta

123

double expectedDouble = 3.14159;

124

double actualDouble = 3.14160;

125

Assert.assertEquals(actualDouble, expectedDouble, 0.001);

126

127

// String inequality

128

Assert.assertNotEquals("hello", "world");

129

}

130

131

@Test

132

public void testObjectIdentity() {

133

String str1 = new String("test");

134

String str2 = new String("test");

135

String str3 = str1;

136

137

// Same content but different objects

138

Assert.assertEquals(str1, str2);

139

Assert.assertNotSame(str1, str2);

140

141

// Same object reference

142

Assert.assertSame(str1, str3);

143

}

144

145

@Test

146

public void testArrayAssertions() {

147

int[] expected = {1, 2, 3, 4, 5};

148

int[] actual = {1, 2, 3, 4, 5};

149

Assert.assertEquals(actual, expected);

150

151

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

152

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

153

Assert.assertEquals(actualStrings, expectedStrings);

154

155

double[] expectedDoubles = {1.1, 2.2, 3.3};

156

double[] actualDoubles = {1.11, 2.21, 3.31};

157

Assert.assertEquals(actualDoubles, expectedDoubles, 0.1);

158

}

159

160

@Test

161

public void testCollectionAssertions() {

162

Set<String> expectedSet = Set.of("a", "b", "c");

163

Set<String> actualSet = Set.of("c", "b", "a"); // Order doesn't matter

164

Assert.assertEquals(actualSet, expectedSet);

165

166

Map<String, Integer> expectedMap = Map.of("one", 1, "two", 2);

167

Map<String, Integer> actualMap = Map.of("two", 2, "one", 1);

168

Assert.assertEquals(actualMap, expectedMap);

169

}

170

171

@Test

172

public void testExceptionAssertions() {

173

// Test that specific exception is thrown

174

IllegalArgumentException exception = Assert.expectThrows(

175

IllegalArgumentException.class,

176

() -> { throw new IllegalArgumentException("Invalid argument"); }

177

);

178

179

Assert.assertEquals(exception.getMessage(), "Invalid argument");

180

181

// Test with custom message

182

RuntimeException runtimeException = Assert.expectThrows(

183

RuntimeException.class,

184

() -> { throw new RuntimeException("Runtime error"); },

185

"Should throw RuntimeException"

186

);

187

}

188

189

@Test

190

public void testFailureMethods() {

191

boolean condition = false;

192

if (!condition) {

193

Assert.fail("Test failed due to condition");

194

}

195

196

try {

197

riskyOperation();

198

} catch (Exception e) {

199

Assert.fail("Unexpected exception", e);

200

}

201

}

202

203

private void riskyOperation() throws Exception {

204

// Some operation that might throw

205

}

206

}

207

```

208

209

### SoftAssert Class

210

211

Collects multiple assertion failures and reports them all at once. Useful for validating multiple conditions without stopping at the first failure.

212

213

```java { .api }

214

/**

215

* Assertion class that collects failures and reports them together

216

*/

217

public class SoftAssert {

218

219

// Constructor

220

public SoftAssert();

221

222

// All assertion methods mirror Assert class but don't throw immediately

223

public void assertTrue(boolean condition);

224

public void assertTrue(boolean condition, String message);

225

public void assertFalse(boolean condition);

226

public void assertFalse(boolean condition, String message);

227

228

public void assertNull(Object object);

229

public void assertNull(Object object, String message);

230

public void assertNotNull(Object object);

231

public void assertNotNull(Object object, String message);

232

233

public void assertEquals(Object actual, Object expected);

234

public void assertEquals(Object actual, Object expected, String message);

235

public void assertEquals(String actual, String expected);

236

public void assertEquals(String actual, String expected, String message);

237

public void assertEquals(double actual, double expected, double delta);

238

public void assertEquals(double actual, double expected, double delta, String message);

239

public void assertEquals(float actual, float expected, float delta);

240

public void assertEquals(float actual, float expected, float delta, String message);

241

242

public void assertNotEquals(Object actual, Object expected);

243

public void assertNotEquals(Object actual, Object expected, String message);

244

245

public void assertSame(Object actual, Object expected);

246

public void assertSame(Object actual, Object expected, String message);

247

public void assertNotSame(Object actual, Object expected);

248

public void assertNotSame(Object actual, Object expected, String message);

249

250

public void assertEquals(Object[] actual, Object[] expected);

251

public void assertEquals(Object[] actual, Object[] expected, String message);

252

253

// Report all collected failures (throws if any failures occurred)

254

public void assertAll();

255

public void assertAll(String message);

256

}

257

```

258

259

**Usage Examples:**

260

261

```java

262

import org.testng.asserts.SoftAssert;

263

import org.testng.annotations.Test;

264

265

public class SoftAssertExamples {

266

267

@Test

268

public void testMultipleValidations() {

269

SoftAssert softAssert = new SoftAssert();

270

271

// Validate multiple fields of an object

272

User user = getUserFromService();

273

274

softAssert.assertNotNull(user, "User should not be null");

275

softAssert.assertEquals(user.getName(), "John Doe", "User name mismatch");

276

softAssert.assertEquals(user.getAge(), 30, "User age mismatch");

277

softAssert.assertTrue(user.isActive(), "User should be active");

278

softAssert.assertNotNull(user.getEmail(), "Email should not be null");

279

softAssert.assertTrue(user.getEmail().contains("@"), "Email should contain @");

280

281

// All assertions are collected and reported together

282

softAssert.assertAll();

283

}

284

285

@Test

286

public void testFormValidation() {

287

SoftAssert softAssert = new SoftAssert();

288

289

// Validate multiple form fields

290

FormData form = getFormData();

291

292

softAssert.assertNotNull(form.getFirstName(), "First name is required");

293

softAssert.assertNotNull(form.getLastName(), "Last name is required");

294

softAssert.assertTrue(form.getFirstName().length() >= 2, "First name too short");

295

softAssert.assertTrue(form.getLastName().length() >= 2, "Last name too short");

296

softAssert.assertTrue(form.getAge() >= 18, "Must be at least 18 years old");

297

softAssert.assertTrue(form.getAge() <= 120, "Invalid age");

298

softAssert.assertTrue(isValidEmail(form.getEmail()), "Invalid email format");

299

300

// Report all validation failures at once

301

softAssert.assertAll("Form validation failed");

302

}

303

304

@Test

305

public void testApiResponse() {

306

SoftAssert softAssert = new SoftAssert();

307

308

ApiResponse response = callApi();

309

310

// Validate response structure

311

softAssert.assertEquals(response.getStatus(), 200, "Wrong status code");

312

softAssert.assertNotNull(response.getData(), "Response data is null");

313

softAssert.assertTrue(response.getData().size() > 0, "No data returned");

314

315

// Validate each item in response

316

for (int i = 0; i < response.getData().size(); i++) {

317

DataItem item = response.getData().get(i);

318

softAssert.assertNotNull(item.getId(), "Item " + i + " has null ID");

319

softAssert.assertNotNull(item.getName(), "Item " + i + " has null name");

320

softAssert.assertTrue(item.getId() > 0, "Item " + i + " has invalid ID");

321

}

322

323

softAssert.assertAll();

324

}

325

326

// Helper methods

327

private User getUserFromService() {

328

return new User("John Doe", 30, true, "john@example.com");

329

}

330

331

private FormData getFormData() {

332

return new FormData("John", "Doe", 25, "john@example.com");

333

}

334

335

private ApiResponse callApi() {

336

// Mock API call

337

return new ApiResponse(200, Arrays.asList(

338

new DataItem(1, "Item 1"),

339

new DataItem(2, "Item 2")

340

));

341

}

342

343

private boolean isValidEmail(String email) {

344

return email != null && email.contains("@") && email.contains(".");

345

}

346

}

347

```

348

349

### FileAssert Class

350

351

File-specific assertions for validating file operations and file system states.

352

353

```java { .api }

354

/**

355

* File-specific assertion utilities

356

*/

357

public class FileAssert {

358

359

// File existence assertions

360

public static void assertFileExists(String filePath);

361

public static void assertFileExists(String filePath, String message);

362

public static void assertFileExists(File file);

363

public static void assertFileExists(File file, String message);

364

365

public static void assertFileNotExists(String filePath);

366

public static void assertFileNotExists(String filePath, String message);

367

public static void assertFileNotExists(File file);

368

public static void assertFileNotExists(File file, String message);

369

370

// File content assertions

371

public static void assertFileEquals(String expectedFilePath, String actualFilePath);

372

public static void assertFileEquals(String expectedFilePath, String actualFilePath, String message);

373

public static void assertFileEquals(File expectedFile, File actualFile);

374

public static void assertFileEquals(File expectedFile, File actualFile, String message);

375

376

// File size assertions

377

public static void assertFileSize(String filePath, long expectedSize);

378

public static void assertFileSize(String filePath, long expectedSize, String message);

379

public static void assertFileSize(File file, long expectedSize);

380

public static void assertFileSize(File file, long expectedSize, String message);

381

}

382

```

383

384

### Assertion Framework Classes

385

386

Internal assertion framework classes that can be extended for custom assertion behavior.

387

388

```java { .api }

389

/**

390

* Base class for assertion implementations

391

*/

392

public class Assertion {

393

public Assertion();

394

protected void doAssert(IAssert<?> assertCommand);

395

protected void onAssertSuccess(IAssert<?> assertCommand);

396

protected void onAssertFailure(IAssert<?> assertCommand, AssertionError ex);

397

protected void onBeforeAssert(IAssert<?> assertCommand);

398

protected void onAfterAssert(IAssert<?> assertCommand);

399

}

400

401

/**

402

* Interface for assertion commands

403

*/

404

public interface IAssert<T> {

405

void doAssert();

406

Object getActual();

407

Object getExpected();

408

String getMessage();

409

}

410

411

/**

412

* Interface for assertion lifecycle hooks

413

*/

414

public interface IAssertLifecycle {

415

void onAssertSuccess(IAssert<?> assertCommand);

416

void onAssertFailure(IAssert<?> assertCommand, AssertionError ex);

417

void onBeforeAssert(IAssert<?> assertCommand);

418

void onAfterAssert(IAssert<?> assertCommand);

419

}

420

421

/**

422

* Assertion class with logging capabilities

423

*/

424

public class LoggingAssert extends Assertion {

425

public LoggingAssert();

426

427

@Override

428

protected void onBeforeAssert(IAssert<?> assertCommand);

429

430

@Override

431

protected void onAssertSuccess(IAssert<?> assertCommand);

432

433

@Override

434

protected void onAssertFailure(IAssert<?> assertCommand, AssertionError ex);

435

}

436

```

437

438

## Types

439

440

```java { .api }

441

// Functional interface for exception testing

442

@FunctionalInterface

443

public interface Executable {

444

void execute() throws Throwable;

445

}

446

447

// Common data classes used in examples

448

public class User {

449

private String name;

450

private int age;

451

private boolean active;

452

private String email;

453

454

public User(String name, int age, boolean active, String email) {

455

this.name = name;

456

this.age = age;

457

this.active = active;

458

this.email = email;

459

}

460

461

// Getters

462

public String getName() { return name; }

463

public int getAge() { return age; }

464

public boolean isActive() { return active; }

465

public String getEmail() { return email; }

466

}

467

468

public class FormData {

469

private String firstName;

470

private String lastName;

471

private int age;

472

private String email;

473

474

public FormData(String firstName, String lastName, int age, String email) {

475

this.firstName = firstName;

476

this.lastName = lastName;

477

this.age = age;

478

this.email = email;

479

}

480

481

// Getters

482

public String getFirstName() { return firstName; }

483

public String getLastName() { return lastName; }

484

public int getAge() { return age; }

485

public String getEmail() { return email; }

486

}

487

```