or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

hamcrest-matchers.mdindex.mdjunit-integration.mdmock-servers.mdtest-appenders.mdtest-categories.mdtesting-utilities.md

testing-utilities.mddocs/

0

# Testing Utilities

1

2

Essential utilities for test infrastructure including port management, system property handling, logger context lifecycle management, compilation helpers, and performance testing tools.

3

4

## Capabilities

5

6

### Port Management

7

8

Utilities for finding available network ports for testing network components.

9

10

```java { .api }

11

/**

12

* Utility for finding available server ports for testing

13

*/

14

public final class AvailablePortFinder {

15

16

/**

17

* Minimum port number for IPv4

18

*/

19

public static final int MIN_PORT_NUMBER = 1100;

20

21

/**

22

* Maximum port number for IPv4

23

*/

24

public static final int MAX_PORT_NUMBER = 65535;

25

26

/**

27

* Gets next available port starting at minimum port

28

* @return Available port number

29

*/

30

public static int getNextAvailable();

31

32

/**

33

* Gets next available port from specified starting port

34

* @param fromPort Starting port to search from

35

* @return Available port number

36

*/

37

public static int getNextAvailable(int fromPort);

38

39

/**

40

* Checks if specific port is available

41

* @param port Port number to check

42

* @return true if port is available, false if in use

43

*/

44

public static boolean available(int port);

45

}

46

47

/**

48

* TestRule to discover available port and save in system property

49

*/

50

public class AvailablePortSystemPropertyTestRule extends SystemPropertyTestRule {

51

52

/**

53

* Creates rule that finds available port and sets system property

54

* @param name System property name to set with port number

55

* @return AvailablePortSystemPropertyTestRule instance

56

*/

57

public static AvailablePortSystemPropertyTestRule create(String name);

58

}

59

```

60

61

**Port Management Usage:**

62

63

```java

64

import org.apache.logging.log4j.core.test.AvailablePortFinder;

65

66

public class NetworkAppenderTest {

67

68

@Test

69

public void testNetworkAppender() {

70

// Find available port for test server

71

int port = AvailablePortFinder.getNextAvailable();

72

73

// Start mock server on available port

74

MockServer server = new MockServer(port);

75

76

// Configure appender to use this port

77

// Perform test...

78

}

79

80

@Test

81

public void testSpecificPortRange() {

82

// Find port starting from 8080

83

int port = AvailablePortFinder.getNextAvailable(8080);

84

assertTrue(port >= 8080);

85

assertTrue(AvailablePortFinder.available(port));

86

}

87

}

88

89

// Using with TestRule

90

public class PortRuleTest {

91

92

@Rule

93

public AvailablePortSystemPropertyTestRule portRule =

94

AvailablePortSystemPropertyTestRule.create("test.port");

95

96

@Test

97

public void testWithPortProperty() {

98

String port = System.getProperty("test.port");

99

assertNotNull(port);

100

// Port is automatically available

101

}

102

}

103

```

104

105

### System Property Management

106

107

TestRules for managing system properties during test execution.

108

109

```java { .api }

110

/**

111

* JUnit TestRule to set and reset system properties during tests

112

*/

113

public class SystemPropertyTestRule implements TestRule {

114

115

/**

116

* Creates rule to set system property to specified value

117

* @param name System property name

118

* @param value System property value

119

* @return SystemPropertyTestRule instance

120

*/

121

public static SystemPropertyTestRule create(String name, String value);

122

123

/**

124

* Creates rule to set system property using value supplier

125

* @param name System property name

126

* @param valueSupplier Supplier providing property value

127

* @return SystemPropertyTestRule instance

128

*/

129

public static SystemPropertyTestRule create(String name, Supplier<String> valueSupplier);

130

131

/**

132

* Applies the rule to test execution

133

* @param base The base statement

134

* @param description Test description

135

* @return Statement with property management

136

*/

137

public Statement apply(Statement base, Description description);

138

139

/**

140

* Gets the property name managed by this rule

141

* @return Property name

142

*/

143

public String getName();

144

145

/**

146

* Gets the property value set by this rule

147

* @return Property value

148

*/

149

public String getValue();

150

151

/**

152

* Gets the value supplier for this rule

153

* @return Value supplier

154

*/

155

public Supplier<String> getValueSupplier();

156

}

157

```

158

159

**System Property Usage:**

160

161

```java

162

import org.apache.logging.log4j.core.test.SystemPropertyTestRule;

163

164

public class SystemPropertyTest {

165

166

@Rule

167

public SystemPropertyTestRule logLevelRule =

168

SystemPropertyTestRule.create("log4j2.level", "DEBUG");

169

170

@Rule

171

public SystemPropertyTestRule tempDirRule =

172

SystemPropertyTestRule.create("test.temp.dir", () -> {

173

return Files.createTempDirectory("log4j-test").toString();

174

});

175

176

@Test

177

public void testWithSystemProperties() {

178

assertEquals("DEBUG", System.getProperty("log4j2.level"));

179

assertTrue(System.getProperty("test.temp.dir").startsWith("/tmp"));

180

// Properties automatically restored after test

181

}

182

}

183

```

184

185

### Logger Context Management

186

187

Utilities for managing LoggerContext lifecycle during testing.

188

189

```java { .api }

190

/**

191

* Logger context lifecycle management utilities

192

*/

193

public class CoreLoggerContexts {

194

195

/**

196

* Stops the current LoggerContext

197

*/

198

public static void stopLoggerContext();

199

200

/**

201

* Stops LoggerContext with option to use current context

202

* @param currentContext Whether to stop current context or default

203

*/

204

public static void stopLoggerContext(boolean currentContext);

205

206

/**

207

* Stops LoggerContext and verifies file presence

208

* @param currentContext Whether to stop current context

209

* @param checkFilePresence File to check for presence after stop

210

*/

211

public static void stopLoggerContext(boolean currentContext, File checkFilePresence);

212

213

/**

214

* Stops LoggerContext with file presence check

215

* @param checkFilePresence File to check for presence after stop

216

*/

217

public static void stopLoggerContext(File checkFilePresence);

218

}

219

```

220

221

### Compilation Utilities

222

223

Java source code compilation utilities for testing dynamic code scenarios.

224

225

```java { .api }

226

/**

227

* Java source code compilation utilities for testing

228

*/

229

public class Compiler {

230

231

/**

232

* Compiles single Java source file

233

* @param source Source file to compile

234

* @param compilerOptions Additional compiler options

235

* @throws RuntimeException if compilation fails

236

*/

237

public static void compile(File source, String... compilerOptions);

238

239

/**

240

* Compiles multiple Java source files

241

* @param sources Iterable of source files to compile

242

* @param compilerOptions Additional compiler options

243

* @throws RuntimeException if compilation fails

244

*/

245

public static void compile(Iterable<? extends File> sources, String... compilerOptions);

246

}

247

```

248

249

**Compilation Usage:**

250

251

```java

252

import org.apache.logging.log4j.core.test.Compiler;

253

254

public class DynamicCompilationTest {

255

256

@Test

257

public void testDynamicPluginCompilation() throws IOException {

258

// Create temporary Java source file

259

File sourceFile = Files.createTempFile("TestPlugin", ".java").toFile();

260

261

String sourceCode = """

262

package test;

263

@Plugin(name = "TestPlugin", category = "Core")

264

public class TestPlugin extends AbstractAppender {

265

// Plugin implementation

266

}

267

""";

268

269

Files.write(sourceFile.toPath(), sourceCode.getBytes());

270

271

// Compile the source

272

Compiler.compile(sourceFile, "-cp", System.getProperty("java.class.path"));

273

274

// Verify compilation produced .class file

275

File classFile = new File(sourceFile.getParent(), "TestPlugin.class");

276

assertTrue(classFile.exists());

277

}

278

}

279

```

280

281

### Performance Testing Utilities

282

283

Utilities for GC-free logging performance testing and profiler integration.

284

285

```java { .api }

286

/**

287

* GC-free logging performance testing utilities

288

*/

289

public enum GcFreeLoggingTestUtil {

290

INSTANCE;

291

292

/**

293

* Executes logging with specified configuration and test class

294

* @param configurationFile Configuration file path

295

* @param testClass Test class to execute

296

*/

297

public static void executeLogging(String configurationFile, Class<?> testClass);

298

299

/**

300

* Runs test class with GC monitoring

301

* @param cls Test class to run

302

*/

303

public static void runTest(Class<?> cls);

304

305

/**

306

* CharSequence implementation for GC-free testing

307

*/

308

public static class MyCharSeq implements CharSequence {

309

310

public MyCharSeq(String value);

311

312

public int length();

313

public char charAt(int index);

314

public CharSequence subSequence(int start, int end);

315

public String toString();

316

}

317

}

318

319

/**

320

* YourKit Java Profiler helper for performance testing

321

*/

322

public final class Profiler {

323

324

/**

325

* Checks if YourKit profiler is active

326

* @return true if profiler is active and available

327

*/

328

public static boolean isActive();

329

330

/**

331

* Starts CPU profiling if profiler is available

332

* @throws RuntimeException if profiler not available

333

*/

334

public static void start();

335

336

/**

337

* Stops profiling and captures snapshot

338

* @throws RuntimeException if profiler not available or not started

339

*/

340

public static void stop();

341

}

342

```

343

344

### Rule Chain Factory

345

346

Utility for building JUnit RuleChains with multiple rules.

347

348

```java { .api }

349

/**

350

* Utility for building JUnit RuleChains

351

*/

352

public class RuleChainFactory {

353

354

/**

355

* Creates RuleChain from multiple TestRules

356

* @param testRules TestRules to chain together

357

* @return RuleChain containing all rules

358

*/

359

public static RuleChain create(TestRule... testRules);

360

}

361

```

362

363

### Test Markers

364

365

Predefined markers for test logging and categorization.

366

367

```java { .api }

368

/**

369

* Predefined markers for testing

370

*/

371

public class TestMarkers {

372

373

/**

374

* Marker for lifecycle-related test logging

375

*/

376

public static final Marker LIFE_CYCLE;

377

378

/**

379

* General test marker

380

*/

381

public static final Marker TEST;

382

383

/**

384

* Marker for TestRule-related logging

385

*/

386

public static final Marker TEST_RULE;

387

388

/**

389

* Marker for TestRule lifecycle logging

390

*/

391

public static final Marker TEST_RULE_LIFE_CYCLE;

392

}

393

```

394

395

### Configuration Factory

396

397

Simple configuration factory for testing scenarios.

398

399

```java { .api }

400

/**

401

* Simple configuration factory for testing

402

*/

403

public class BasicConfigurationFactory extends ConfigurationFactory {

404

405

/**

406

* Gets configuration for LoggerContext with URI

407

* @param loggerContext The logger context

408

* @param name Configuration name

409

* @param configLocation Configuration URI

410

* @return Configuration instance

411

*/

412

public Configuration getConfiguration(LoggerContext loggerContext, String name, URI configLocation);

413

414

/**

415

* Gets supported configuration types

416

* @return Array of supported file extensions

417

*/

418

public String[] getSupportedTypes();

419

420

/**

421

* Gets configuration from ConfigurationSource

422

* @param loggerContext The logger context

423

* @param source Configuration source

424

* @return Configuration instance

425

*/

426

public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source);

427

428

/**

429

* Simple configuration implementation for testing

430

*/

431

public static class BasicConfiguration extends AbstractConfiguration {

432

433

/**

434

* Creates basic configuration with default console appender

435

* @param loggerContext The logger context

436

* @param name Configuration name

437

*/

438

public BasicConfiguration(LoggerContext loggerContext, String name);

439

}

440

}

441

```

442

443

### Extended Levels

444

445

Custom logging levels for testing scenarios.

446

447

```java { .api }

448

/**

449

* Custom logging levels for testing

450

* Plugin annotation: @Plugin(name = "ExtendedLevel", category = Level.CATEGORY)

451

*/

452

@Plugin(name = "ExtendedLevel", category = Level.CATEGORY)

453

public class ExtendedLevels {

454

455

/**

456

* NOTE level (350) - between INFO (400) and WARN (300)

457

*/

458

public static final Level NOTE = Level.forName("NOTE", 350);

459

460

/**

461

* DETAIL level (450) - between DEBUG (500) and INFO (400)

462

*/

463

public static final Level DETAIL = Level.forName("DETAIL", 450);

464

}

465

```

466

467

## Usage Patterns

468

469

### Resource Management Pattern

470

471

```java

472

@Rule

473

public RuleChain rules = RuleChainFactory.create(

474

SystemPropertyTestRule.create("test.port", "8080"),

475

AvailablePortSystemPropertyTestRule.create("available.port"),

476

CleanFiles.cleanFiles("test.log")

477

);

478

```

479

480

### Performance Testing Pattern

481

482

```java

483

@Test

484

public void testGcFreeLogging() {

485

if (Profiler.isActive()) {

486

Profiler.start();

487

}

488

489

GcFreeLoggingTestUtil.executeLogging("gc-free-config.xml", this.getClass());

490

491

if (Profiler.isActive()) {

492

Profiler.stop();

493

}

494

}

495

```

496

497

### Context Lifecycle Pattern

498

499

```java

500

@After

501

public void cleanup() {

502

CoreLoggerContexts.stopLoggerContext();

503

}

504

```