or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

additional-answers.mdadditional-matchers.mdadvanced-features.mdannotations.mdargument-matching.mdbdd-testing.mdindex.mdmock-creation.mdstatic-mocking.mdstubbing.mdverification.md

annotations.mddocs/

0

# Annotations and Test Setup

1

2

This section covers Mockito's annotation-based approach to mock creation, dependency injection, and test class setup.

3

4

## Core Annotations

5

6

### @Mock Annotation

7

8

Create mock objects automatically from annotated fields.

9

10

```java { .api }

11

@Target({ElementType.FIELD, ElementType.PARAMETER})

12

@Retention(RetentionPolicy.RUNTIME)

13

@interface Mock {

14

Answers answer() default Answers.RETURNS_DEFAULTS;

15

String name() default "";

16

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

17

boolean serializable() default false;

18

Strictness strictness() default Strictness.STRICT_STUBS;

19

String mockMaker() default "";

20

boolean stubOnly() default false;

21

boolean withoutAnnotations() default false;

22

}

23

```

24

25

**Usage Examples:**

26

27

```java

28

class UserServiceTest {

29

@Mock

30

private UserRepository userRepository;

31

32

@Mock(answer = Answers.RETURNS_SMART_NULLS)

33

private EmailService emailService;

34

35

@Mock(name = "authMock", strictness = Strictness.LENIENT)

36

private AuthService authService;

37

38

@Mock(extraInterfaces = {Serializable.class, Cloneable.class})

39

private DataProcessor dataProcessor;

40

41

@BeforeEach

42

void setUp() {

43

MockitoAnnotations.openMocks(this);

44

}

45

}

46

```

47

48

### @Spy Annotation

49

50

Create spy objects that wrap real instances or classes.

51

52

```java { .api }

53

@Target({ElementType.FIELD, ElementType.PARAMETER})

54

@Retention(RetentionPolicy.RUNTIME)

55

@interface Spy

56

```

57

58

**Usage Examples:**

59

60

```java

61

class OrderServiceTest {

62

// Spy on existing instance

63

@Spy

64

private List<String> spiedList = new ArrayList<>();

65

66

// Spy on class (calls default constructor)

67

@Spy

68

private UserService userService;

69

70

// Spy with initialization

71

@Spy

72

private Calculator calculator = new Calculator();

73

74

@BeforeEach

75

void setUp() {

76

MockitoAnnotations.openMocks(this);

77

}

78

79

@Test

80

void testSpyBehavior() {

81

// Real method called

82

spiedList.add("real item");

83

assertEquals(1, spiedList.size());

84

85

// Stubbed behavior

86

when(spiedList.size()).thenReturn(100);

87

assertEquals(100, spiedList.size());

88

}

89

}

90

```

91

92

### @InjectMocks Annotation

93

94

Automatically inject mocks into the tested object.

95

96

```java { .api }

97

@Target(ElementType.FIELD)

98

@Retention(RetentionPolicy.RUNTIME)

99

@interface InjectMocks

100

```

101

102

**Usage Examples:**

103

104

```java

105

class UserServiceTest {

106

@Mock

107

private UserRepository userRepository;

108

109

@Mock

110

private EmailService emailService;

111

112

@Mock

113

private ValidationService validationService;

114

115

@InjectMocks

116

private UserService userService; // Mocks injected here

117

118

@BeforeEach

119

void setUp() {

120

MockitoAnnotations.openMocks(this);

121

}

122

123

@Test

124

void testUserCreation() {

125

// Mocks are already injected into userService

126

when(validationService.isValidEmail(anyString())).thenReturn(true);

127

when(userRepository.save(any(User.class))).thenReturn(savedUser);

128

129

User result = userService.createUser("john", "john@example.com");

130

131

verify(validationService).isValidEmail("john@example.com");

132

verify(userRepository).save(any(User.class));

133

assertNotNull(result);

134

}

135

}

136

```

137

138

### @Captor Annotation

139

140

Create ArgumentCaptor instances automatically.

141

142

```java { .api }

143

@Target(ElementType.FIELD)

144

@Retention(RetentionPolicy.RUNTIME)

145

@interface Captor

146

```

147

148

**Usage Examples:**

149

150

```java

151

class EventServiceTest {

152

@Mock

153

private EventPublisher eventPublisher;

154

155

@Captor

156

private ArgumentCaptor<Event> eventCaptor;

157

158

@Captor

159

private ArgumentCaptor<String> stringCaptor;

160

161

@InjectMocks

162

private OrderService orderService;

163

164

@BeforeEach

165

void setUp() {

166

MockitoAnnotations.openMocks(this);

167

}

168

169

@Test

170

void testEventPublishing() {

171

orderService.createOrder("item1", "item2");

172

173

// Capture published events

174

verify(eventPublisher, times(2)).publish(eventCaptor.capture());

175

176

List<Event> events = eventCaptor.getAllValues();

177

assertEquals(2, events.size());

178

assertEquals("ORDER_CREATED", events.get(0).getType());

179

}

180

}

181

```

182

183

## Advanced Annotations

184

185

### @DoNotMock Annotation

186

187

Mark classes that should not be mocked.

188

189

```java { .api }

190

@Target(ElementType.TYPE)

191

@Retention(RetentionPolicy.RUNTIME)

192

@interface DoNotMock {

193

String reason() default "";

194

}

195

```

196

197

**Usage Examples:**

198

199

```java

200

@DoNotMock(reason = "Use real instance or create a fake")

201

public class ValueObject {

202

private final String value;

203

204

public ValueObject(String value) {

205

this.value = value;

206

}

207

208

public String getValue() {

209

return value;

210

}

211

}

212

213

// In tests, Mockito will warn if you try to mock this

214

class SomeTest {

215

@Test

216

void testWithValueObject() {

217

// This will generate a warning

218

// ValueObject mock = mock(ValueObject.class);

219

220

// Use real instance instead

221

ValueObject realObject = new ValueObject("test");

222

}

223

}

224

```

225

226

## Mock Initialization

227

228

### MockitoAnnotations Class

229

230

Initialize annotated mocks in test classes.

231

232

```java { .api }

233

public static AutoCloseable openMocks(Object testClass)

234

public static void initMocks(Object testClass) // Deprecated

235

```

236

237

**Usage Examples:**

238

239

```java

240

class ModernTestSetup {

241

@Mock

242

private UserService userService;

243

244

private AutoCloseable closeable;

245

246

@BeforeEach

247

void setUp() {

248

closeable = MockitoAnnotations.openMocks(this);

249

}

250

251

@AfterEach

252

void tearDown() throws Exception {

253

closeable.close();

254

}

255

}

256

257

// Alternative with try-with-resources

258

class AlternativeSetup {

259

@Test

260

void testWithAutoClose() throws Exception {

261

try (AutoCloseable closeable = MockitoAnnotations.openMocks(this)) {

262

// Test code here

263

}

264

}

265

}

266

```

267

268

## Injection Strategies

269

270

### Constructor Injection

271

272

Mockito tries constructor injection first.

273

274

```java

275

// Service class with constructor

276

public class OrderService {

277

private final PaymentService paymentService;

278

private final InventoryService inventoryService;

279

280

public OrderService(PaymentService paymentService,

281

InventoryService inventoryService) {

282

this.paymentService = paymentService;

283

this.inventoryService = inventoryService;

284

}

285

}

286

287

// Test class

288

class OrderServiceTest {

289

@Mock private PaymentService paymentService;

290

@Mock private InventoryService inventoryService;

291

292

@InjectMocks private OrderService orderService; // Constructor injection

293

294

@BeforeEach

295

void setUp() {

296

MockitoAnnotations.openMocks(this);

297

}

298

}

299

```

300

301

### Setter Injection

302

303

Falls back to setter injection if constructor injection isn't possible.

304

305

```java

306

public class UserService {

307

private EmailService emailService;

308

private ValidationService validationService;

309

310

public void setEmailService(EmailService emailService) {

311

this.emailService = emailService;

312

}

313

314

public void setValidationService(ValidationService validationService) {

315

this.validationService = validationService;

316

}

317

}

318

319

// Mocks injected via setters

320

class UserServiceTest {

321

@Mock private EmailService emailService;

322

@Mock private ValidationService validationService;

323

324

@InjectMocks private UserService userService; // Setter injection

325

}

326

```

327

328

### Field Injection

329

330

Last resort: direct field injection.

331

332

```java

333

public class ReportService {

334

@Autowired

335

private DataService dataService; // Private field

336

337

private EmailService emailService; // No setter

338

}

339

340

// Field injection used

341

class ReportServiceTest {

342

@Mock private DataService dataService;

343

@Mock private EmailService emailService;

344

345

@InjectMocks private ReportService reportService; // Field injection

346

}

347

```

348

349

## JUnit Integration

350

351

### JUnit 5 Extension

352

353

Use MockitoExtension for automatic setup.

354

355

```java { .api }

356

@ExtendWith(MockitoExtension.class)

357

```

358

359

**Usage Example:**

360

361

```java

362

@ExtendWith(MockitoExtension.class)

363

class JUnit5Test {

364

@Mock

365

private UserRepository userRepository;

366

367

@InjectMocks

368

private UserService userService;

369

370

// No @BeforeEach needed - extension handles setup

371

372

@Test

373

void testUserCreation() {

374

when(userRepository.save(any())).thenReturn(savedUser);

375

376

User result = userService.createUser("test");

377

378

verify(userRepository).save(any(User.class));

379

}

380

}

381

```

382

383

### JUnit 4 Runner and Rule

384

385

Legacy JUnit 4 integration options.

386

387

```java { .api }

388

@RunWith(MockitoJUnitRunner.class)

389

@RunWith(MockitoJUnitRunner.Strict.class)

390

391

public static MockitoRule rule()

392

```

393

394

**Usage Examples:**

395

396

```java

397

// JUnit 4 Runner

398

@RunWith(MockitoJUnitRunner.class)

399

public class JUnit4RunnerTest {

400

@Mock private UserService userService;

401

@InjectMocks private OrderService orderService;

402

403

// No setup needed

404

}

405

406

// JUnit 4 Rule (more flexible)

407

public class JUnit4RuleTest {

408

@Rule

409

public MockitoRule mockitoRule = MockitoJUnit.rule();

410

411

@Mock private UserService userService;

412

@InjectMocks private OrderService orderService;

413

}

414

415

// Strict rule (fails on unused stubs)

416

public class StrictRuleTest {

417

@Rule

418

public MockitoRule mockitoRule = MockitoJUnit.rule()

419

.strictness(Strictness.STRICT_STUBS);

420

421

@Mock private UserService userService;

422

}

423

```

424

425

## Manual Mock Creation vs Annotations

426

427

### When to Use Each Approach

428

429

**Annotations are better for:**

430

- Standard test setup

431

- Consistent mock configuration

432

- Automatic dependency injection

433

- Integration with test frameworks

434

435

**Manual creation is better for:**

436

- Dynamic mock creation

437

- Test-specific configuration

438

- Complex mock setup

439

- Conditional mock creation

440

441

**Comparison Example:**

442

443

```java

444

class ComparisonExample {

445

// Annotation approach

446

@Mock private UserRepository userRepository;

447

@InjectMocks private UserService userService;

448

449

@BeforeEach

450

void annotationSetup() {

451

MockitoAnnotations.openMocks(this);

452

}

453

454

@Test

455

void annotationTest() {

456

// Test with injected mocks

457

}

458

459

// Manual approach

460

@Test

461

void manualTest() {

462

UserRepository mockRepo = mock(UserRepository.class);

463

UserService service = new UserService(mockRepo);

464

465

// Test with manually created mocks

466

}

467

468

// Mixed approach

469

@Test

470

void mixedTest() {

471

// Some mocks from annotations

472

// Some created manually for specific needs

473

PaymentService specialMock = mock(PaymentService.class,

474

withSettings().strictness(Strictness.LENIENT));

475

}

476

}

477

```