or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context-testing.mdcore-testing.mdindex.mdjson-testing.mdmock-integration.mdoutput-capture.mdtest-slices.mdweb-testing.md

test-slices.mddocs/

0

# Test Slices

1

2

Auto-configured test slices for focused testing of specific application layers with minimal context loading. Test slices load only the components necessary for testing a particular layer, improving test performance and isolation.

3

4

## Capabilities

5

6

### Web Layer Testing

7

8

#### @WebMvcTest

9

10

Auto-configured test slice for testing Spring MVC controllers with MockMvc.

11

12

```java { .api }

13

/**

14

* Annotation for Spring MVC tests that focus only on Spring MVC components

15

* @since 1.4.0

16

*/

17

@Target(ElementType.TYPE)

18

@Retention(RetentionPolicy.RUNTIME)

19

@Documented

20

@Inherited

21

@BootstrapWith(WebMvcTestContextBootstrapper.class)

22

@ExtendWith(SpringExtension.class)

23

@OverrideAutoConfiguration(enabled = false)

24

@TypeExcludeFilters(WebMvcTypeExcludeFilter.class)

25

@AutoConfigureCache

26

@AutoConfigureWebMvc

27

@AutoConfigureMockMvc

28

@ImportAutoConfiguration

29

public @interface WebMvcTest {

30

/**

31

* Specifies the controllers to test (same as controllers)

32

*/

33

Class<?>[] value() default {};

34

35

/**

36

* Specifies the controllers to test

37

*/

38

Class<?>[] controllers() default {};

39

40

/**

41

* Determines if default filters should be used with @ComponentScan

42

*/

43

boolean useDefaultFilters() default true;

44

45

/**

46

* ComponentScan filters to include additional components

47

*/

48

ComponentScan.Filter[] includeFilters() default {};

49

50

/**

51

* ComponentScan filters to exclude components

52

*/

53

ComponentScan.Filter[] excludeFilters() default {};

54

55

/**

56

* Properties in form key=value to add to the Environment

57

*/

58

String[] properties() default {};

59

}

60

```

61

62

**Usage Examples:**

63

64

```java

65

@WebMvcTest(UserController.class)

66

class UserControllerTest {

67

68

@Autowired

69

private MockMvc mockMvc;

70

71

@MockBean

72

private UserService userService;

73

74

@Test

75

void getUserReturnsUser() throws Exception {

76

User mockUser = new User("test@example.com", "Test User");

77

when(userService.findByEmail("test@example.com")).thenReturn(mockUser);

78

79

mockMvc.perform(get("/users/test@example.com"))

80

.andExpect(status().isOk())

81

.andExpect(content().contentType(MediaType.APPLICATION_JSON))

82

.andExpect(jsonPath("$.email").value("test@example.com"))

83

.andExpect(jsonPath("$.name").value("Test User"));

84

85

verify(userService).findByEmail("test@example.com");

86

}

87

88

@Test

89

void createUserValidatesInput() throws Exception {

90

mockMvc.perform(post("/users")

91

.contentType(MediaType.APPLICATION_JSON)

92

.content("{}"))

93

.andExpect(status().isBadRequest())

94

.andExpect(jsonPath("$.errors").exists());

95

}

96

}

97

```

98

99

#### @WebFluxTest

100

101

Auto-configured test slice for testing Spring WebFlux controllers with WebTestClient.

102

103

```java { .api }

104

/**

105

* Annotation for WebFlux tests that focus only on Spring WebFlux components

106

* @since 2.0.0

107

*/

108

@Target(ElementType.TYPE)

109

@Retention(RetentionPolicy.RUNTIME)

110

@Documented

111

@Inherited

112

@BootstrapWith(WebFluxTestContextBootstrapper.class)

113

@ExtendWith(SpringExtension.class)

114

@OverrideAutoConfiguration(enabled = false)

115

@TypeExcludeFilters(WebFluxTypeExcludeFilter.class)

116

@AutoConfigureCache

117

@AutoConfigureWebFlux

118

@AutoConfigureWebTestClient

119

@ImportAutoConfiguration

120

public @interface WebFluxTest {

121

/**

122

* Specifies the controllers to test (same as controllers)

123

*/

124

Class<?>[] value() default {};

125

126

/**

127

* Specifies the controllers to test

128

*/

129

Class<?>[] controllers() default {};

130

131

/**

132

* Determines if default filters should be used with @ComponentScan

133

*/

134

boolean useDefaultFilters() default true;

135

136

/**

137

* ComponentScan filters to include additional components

138

*/

139

ComponentScan.Filter[] includeFilters() default {};

140

141

/**

142

* ComponentScan filters to exclude components

143

*/

144

ComponentScan.Filter[] excludeFilters() default {};

145

146

/**

147

* Properties in form key=value to add to the Environment

148

*/

149

String[] properties() default {};

150

}

151

```

152

153

**Usage Examples:**

154

155

```java

156

@WebFluxTest(UserController.class)

157

class UserControllerWebFluxTest {

158

159

@Autowired

160

private WebTestClient webTestClient;

161

162

@MockBean

163

private UserService userService;

164

165

@Test

166

void getUserReturnsUser() {

167

User mockUser = new User("test@example.com", "Test User");

168

when(userService.findByEmail("test@example.com")).thenReturn(Mono.just(mockUser));

169

170

webTestClient.get()

171

.uri("/users/test@example.com")

172

.exchange()

173

.expectStatus().isOk()

174

.expectHeader().contentType(MediaType.APPLICATION_JSON)

175

.expectBody(User.class)

176

.value(user -> {

177

assertThat(user.getEmail()).isEqualTo("test@example.com");

178

assertThat(user.getName()).isEqualTo("Test User");

179

});

180

}

181

}

182

```

183

184

### Data Layer Testing

185

186

#### @DataJpaTest

187

188

Auto-configured test slice for JPA repositories using an in-memory database.

189

190

```java { .api }

191

/**

192

* Annotation for JPA tests that focus only on JPA components

193

* @since 1.4.0

194

*/

195

@Target(ElementType.TYPE)

196

@Retention(RetentionPolicy.RUNTIME)

197

@Documented

198

@Inherited

199

@BootstrapWith(DataJpaTestContextBootstrapper.class)

200

@ExtendWith(SpringExtension.class)

201

@OverrideAutoConfiguration(enabled = false)

202

@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)

203

@Transactional

204

@AutoConfigureCache

205

@AutoConfigureDataJpa

206

@AutoConfigureTestDatabase

207

@AutoConfigureTestEntityManager

208

@ImportAutoConfiguration

209

public @interface DataJpaTest {

210

/**

211

* Entity types to scan for

212

*/

213

Class<?>[] entities() default {};

214

215

/**

216

* Whether to show SQL statements

217

*/

218

boolean showSql() default true;

219

220

/**

221

* Determines if default filters should be used with @ComponentScan

222

*/

223

boolean useDefaultFilters() default true;

224

225

/**

226

* ComponentScan filters to include additional components

227

*/

228

ComponentScan.Filter[] includeFilters() default {};

229

230

/**

231

* ComponentScan filters to exclude components

232

*/

233

ComponentScan.Filter[] excludeFilters() default {};

234

235

/**

236

* Properties in form key=value to add to the Environment

237

*/

238

String[] properties() default {};

239

}

240

```

241

242

**Usage Examples:**

243

244

```java

245

@DataJpaTest

246

class UserRepositoryTest {

247

248

@Autowired

249

private TestEntityManager entityManager;

250

251

@Autowired

252

private UserRepository userRepository;

253

254

@Test

255

void findByEmailReturnsUser() {

256

// Given

257

User user = new User("test@example.com", "Test User");

258

entityManager.persistAndFlush(user);

259

260

// When

261

Optional<User> found = userRepository.findByEmail("test@example.com");

262

263

// Then

264

assertThat(found).isPresent();

265

assertThat(found.get().getName()).isEqualTo("Test User");

266

}

267

268

@Test

269

void findByNonExistentEmailReturnsEmpty() {

270

Optional<User> found = userRepository.findByEmail("nonexistent@example.com");

271

assertThat(found).isEmpty();

272

}

273

274

@Test

275

void saveUserPersistsData() {

276

User user = new User("save@example.com", "Save User");

277

User saved = userRepository.save(user);

278

279

assertThat(saved.getId()).isNotNull();

280

assertThat(entityManager.find(User.class, saved.getId())).isEqualTo(saved);

281

}

282

}

283

```

284

285

#### @DataMongoTest

286

287

Auto-configured test slice for MongoDB repositories.

288

289

```java { .api }

290

/**

291

* Annotation for MongoDB tests that focus only on MongoDB components

292

* @since 1.4.0

293

*/

294

@Target(ElementType.TYPE)

295

@Retention(RetentionPolicy.RUNTIME)

296

@Documented

297

@Inherited

298

@BootstrapWith(DataMongoTestContextBootstrapper.class)

299

@ExtendWith(SpringExtension.class)

300

@OverrideAutoConfiguration(enabled = false)

301

@TypeExcludeFilters(DataMongoTypeExcludeFilter.class)

302

@AutoConfigureCache

303

@AutoConfigureDataMongo

304

@ImportAutoConfiguration

305

public @interface DataMongoTest {

306

/**

307

* Determines if default filters should be used with @ComponentScan

308

*/

309

boolean useDefaultFilters() default true;

310

311

/**

312

* ComponentScan filters to include additional components

313

*/

314

ComponentScan.Filter[] includeFilters() default {};

315

316

/**

317

* ComponentScan filters to exclude components

318

*/

319

ComponentScan.Filter[] excludeFilters() default {};

320

321

/**

322

* Properties in form key=value to add to the Environment

323

*/

324

String[] properties() default {};

325

}

326

```

327

328

#### @DataRedisTest

329

330

Auto-configured test slice for Redis repositories.

331

332

```java { .api }

333

/**

334

* Annotation for Redis tests that focus only on Redis components

335

* @since 1.4.0

336

*/

337

@Target(ElementType.TYPE)

338

@Retention(RetentionPolicy.RUNTIME)

339

@Documented

340

@Inherited

341

@BootstrapWith(DataRedisTestContextBootstrapper.class)

342

@ExtendWith(SpringExtension.class)

343

@OverrideAutoConfiguration(enabled = false)

344

@TypeExcludeFilters(DataRedisTypeExcludeFilter.class)

345

@AutoConfigureCache

346

@AutoConfigureDataRedis

347

@ImportAutoConfiguration

348

public @interface DataRedisTest {

349

/**

350

* Determines if default filters should be used with @ComponentScan

351

*/

352

boolean useDefaultFilters() default true;

353

354

/**

355

* ComponentScan filters to include additional components

356

*/

357

ComponentScan.Filter[] includeFilters() default {};

358

359

/**

360

* ComponentScan filters to exclude components

361

*/

362

ComponentScan.Filter[] excludeFilters() default {};

363

364

/**

365

* Properties in form key=value to add to the Environment

366

*/

367

String[] properties() default {};

368

}

369

```

370

371

### JSON Testing

372

373

#### @JsonTest

374

375

Auto-configured test slice for testing JSON serialization and deserialization.

376

377

```java { .api }

378

/**

379

* Annotation for JSON tests that focus only on JSON serialization

380

* @since 1.4.0

381

*/

382

@Target(ElementType.TYPE)

383

@Retention(RetentionPolicy.RUNTIME)

384

@Documented

385

@Inherited

386

@BootstrapWith(JsonTestContextBootstrapper.class)

387

@ExtendWith(SpringExtension.class)

388

@OverrideAutoConfiguration(enabled = false)

389

@AutoConfigureCache

390

@AutoConfigureJson

391

@AutoConfigureJsonTesters

392

@ImportAutoConfiguration

393

public @interface JsonTest {

394

/**

395

* Determines if default filters should be used with @ComponentScan

396

*/

397

boolean useDefaultFilters() default true;

398

399

/**

400

* ComponentScan filters to include additional components

401

*/

402

ComponentScan.Filter[] includeFilters() default {};

403

404

/**

405

* ComponentScan filters to exclude components

406

*/

407

ComponentScan.Filter[] excludeFilters() default {};

408

409

/**

410

* Properties in form key=value to add to the Environment

411

*/

412

String[] properties() default {};

413

}

414

```

415

416

**Usage Examples:**

417

418

```java

419

@JsonTest

420

class UserJsonTest {

421

422

@Autowired

423

private JacksonTester<User> json;

424

425

@Test

426

void serializeUser() throws Exception {

427

User user = new User("test@example.com", "Test User");

428

429

assertThat(this.json.write(user))

430

.hasJsonPathStringValue("@.email", "test@example.com")

431

.hasJsonPathStringValue("@.name", "Test User");

432

}

433

434

@Test

435

void deserializeUser() throws Exception {

436

String content = "{\"email\":\"test@example.com\",\"name\":\"Test User\"}";

437

438

User user = this.json.parseObject(content);

439

440

assertThat(user.getEmail()).isEqualTo("test@example.com");

441

assertThat(user.getName()).isEqualTo("Test User");

442

}

443

}

444

```

445

446

### REST Client Testing

447

448

#### @RestClientTest

449

450

Auto-configured test slice for testing REST clients.

451

452

```java { .api }

453

/**

454

* Annotation for REST client tests that focus only on REST client components

455

* @since 1.4.0

456

*/

457

@Target(ElementType.TYPE)

458

@Retention(RetentionPolicy.RUNTIME)

459

@Documented

460

@Inherited

461

@BootstrapWith(RestClientTestContextBootstrapper.class)

462

@ExtendWith(SpringExtension.class)

463

@OverrideAutoConfiguration(enabled = false)

464

@TypeExcludeFilters(RestClientTestTypeExcludeFilter.class)

465

@AutoConfigureCache

466

@AutoConfigureWebClient

467

@AutoConfigureMockRestServiceServer

468

@ImportAutoConfiguration

469

public @interface RestClientTest {

470

/**

471

* Specifies the components to test (same as components)

472

*/

473

Class<?>[] value() default {};

474

475

/**

476

* Specifies the components to test

477

*/

478

Class<?>[] components() default {};

479

480

/**

481

* Determines if default filters should be used with @ComponentScan

482

*/

483

boolean useDefaultFilters() default true;

484

485

/**

486

* ComponentScan filters to include additional components

487

*/

488

ComponentScan.Filter[] includeFilters() default {};

489

490

/**

491

* ComponentScan filters to exclude components

492

*/

493

ComponentScan.Filter[] excludeFilters() default {};

494

495

/**

496

* Properties in form key=value to add to the Environment

497

*/

498

String[] properties() default {};

499

}

500

```

501

502

**Usage Examples:**

503

504

```java

505

@RestClientTest(UserClient.class)

506

class UserClientTest {

507

508

@Autowired

509

private UserClient userClient;

510

511

@Autowired

512

private MockRestServiceServer server;

513

514

@Test

515

void getUserCallsExternalService() {

516

// Mock external service response

517

this.server.expect(requestTo("/api/users/test@example.com"))

518

.andExpect(method(HttpMethod.GET))

519

.andRespond(withSuccess(

520

"{\"email\":\"test@example.com\",\"name\":\"Test User\"}",

521

MediaType.APPLICATION_JSON));

522

523

// Call client method

524

User user = userClient.getUser("test@example.com");

525

526

// Verify response

527

assertThat(user.getEmail()).isEqualTo("test@example.com");

528

assertThat(user.getName()).isEqualTo("Test User");

529

}

530

}

531

```

532

533

### Test Database Configuration

534

535

#### @AutoConfigureTestDatabase

536

537

Configuration for test databases in data layer tests.

538

539

```java { .api }

540

/**

541

* Annotation to configure a test database for use in tests

542

* @since 1.4.0

543

*/

544

@Target({ElementType.TYPE, ElementType.METHOD})

545

@Retention(RetentionPolicy.RUNTIME)

546

@Documented

547

@ImportAutoConfiguration

548

public @interface AutoConfigureTestDatabase {

549

/**

550

* The type of connection to use

551

*/

552

Connection connection() default Connection.EMBEDDED;

553

554

/**

555

* What the test database should replace

556

*/

557

Replace replace() default Replace.ANY;

558

559

/**

560

* Type of connection to use

561

*/

562

enum Connection {

563

/**

564

* Use an embedded in-memory database

565

*/

566

EMBEDDED,

567

568

/**

569

* Use any available connection

570

*/

571

ANY

572

}

573

574

/**

575

* What the test database should replace

576

*/

577

enum Replace {

578

/**

579

* Replace any DataSource bean

580

*/

581

ANY,

582

583

/**

584

* Replace auto-configured DataSource

585

*/

586

AUTO_CONFIGURED,

587

588

/**

589

* Don't replace any DataSource

590

*/

591

NONE

592

}

593

}

594

```

595

596

**Usage Examples:**

597

598

```java

599

@DataJpaTest

600

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

601

class UserRepositoryIntegrationTest {

602

// Uses actual database configuration instead of embedded

603

604

@Autowired

605

private UserRepository userRepository;

606

607

@Test

608

void findByEmailWithRealDatabase() {

609

// Test using actual database

610

User user = new User("real@example.com", "Real User");

611

userRepository.save(user);

612

613

Optional<User> found = userRepository.findByEmail("real@example.com");

614

assertThat(found).isPresent();

615

}

616

}

617

```

618

619

### Advanced Test Slice Usage

620

621

Advanced patterns and configurations for test slices.

622

623

**Usage Examples:**

624

625

```java

626

// Multiple test slices with custom configuration

627

@WebMvcTest

628

@Import({SecurityConfig.class, CustomValidator.class})

629

class SecureControllerTest {

630

631

@Autowired

632

private MockMvc mockMvc;

633

634

@MockBean

635

private UserService userService;

636

637

@WithMockUser(roles = "ADMIN")

638

@Test

639

void adminCanAccessProtectedEndpoint() throws Exception {

640

mockMvc.perform(get("/admin/users"))

641

.andExpect(status().isOk());

642

}

643

}

644

645

// Custom filters for component scanning

646

@WebMvcTest(

647

includeFilters = @ComponentScan.Filter(

648

type = FilterType.ASSIGNABLE_TYPE,

649

classes = CustomExceptionHandler.class

650

),

651

excludeFilters = @ComponentScan.Filter(

652

type = FilterType.ASSIGNABLE_TYPE,

653

classes = GlobalSecurityConfig.class

654

)

655

)

656

class FilteredWebMvcTest {

657

// Test implementation

658

}

659

660

// Test slice with custom properties

661

@DataJpaTest(properties = {

662

"spring.jpa.hibernate.ddl-auto=create-drop",

663

"logging.level.org.hibernate.SQL=DEBUG"

664

})

665

class CustomPropertiesDataJpaTest {

666

// Test implementation with custom JPA properties

667

}

668

```