or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations.mdargument-capturing.mdbdd-testing.mdindex.mdjunit-integration.mdmatchers.mdmock-creation.mdstubbing.mdverification.md

stubbing.mddocs/

0

# Method Stubbing

1

2

Stubbing allows you to define the behavior of mock methods. When a stubbed method is called, it returns the predefined value or performs the specified action instead of the default behavior.

3

4

## Basic Stubbing

5

6

### When-Then Stubbing

7

8

The standard way to stub methods:

9

10

```java { .api }

11

public static <T> OngoingStubbing<T> when(T methodCall);

12

13

public interface OngoingStubbing<T> {

14

OngoingStubbing<T> thenReturn(T value);

15

OngoingStubbing<T> thenReturn(T value, T... values);

16

OngoingStubbing<T> thenThrow(Throwable... throwables);

17

OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType);

18

OngoingStubbing<T> thenAnswer(Answer<?> answer);

19

OngoingStubbing<T> thenCallRealMethod();

20

T getMock();

21

}

22

```

23

24

**Usage Examples:**

25

26

```java

27

List<String> mock = mock(List.class);

28

29

// Return values

30

when(mock.get(0)).thenReturn("first");

31

when(mock.get(1)).thenReturn("second");

32

33

// Multiple return values in sequence

34

when(mock.size()).thenReturn(1, 2, 3);

35

36

// Throw exceptions

37

when(mock.get(anyInt())).thenThrow(new RuntimeException("Error"));

38

when(mock.clear()).thenThrow(UnsupportedOperationException.class);

39

```

40

41

### Consecutive Stubbing

42

43

Stub methods to return different values on consecutive calls:

44

45

```java

46

when(mock.someMethod("some arg"))

47

.thenReturn("one", "two", "three");

48

49

// First call returns "one", second returns "two", third and subsequent return "three"

50

```

51

52

## Do-Family Stubbing

53

54

Alternative stubbing syntax, especially useful for void methods and spies:

55

56

```java { .api }

57

public static Stubber doReturn(Object toBeReturned);

58

public static Stubber doThrow(Throwable toBeThrown);

59

public static Stubber doThrow(Class<? extends Throwable> toBeThrown);

60

public static Stubber doAnswer(Answer answer);

61

public static Stubber doNothing();

62

public static Stubber doCallRealMethod();

63

64

public interface Stubber {

65

<T> T when(T mock);

66

Stubber doReturn(Object toBeReturned);

67

Stubber doThrow(Throwable... toBeThrown);

68

Stubber doAnswer(Answer answer);

69

Stubber doNothing();

70

Stubber doCallRealMethod();

71

}

72

```

73

74

**Usage Examples:**

75

76

```java

77

List<String> mock = mock(List.class);

78

79

// Return values

80

doReturn("element").when(mock).get(0);

81

82

// Throw exceptions

83

doThrow(new RuntimeException()).when(mock).clear();

84

85

// Do nothing (for void methods)

86

doNothing().when(mock).clear();

87

88

// Call real method

89

doCallRealMethod().when(mock).size();

90

91

// Chaining multiple behaviors

92

doReturn("first")

93

.doReturn("second")

94

.doThrow(new RuntimeException())

95

.when(mock).get(anyInt());

96

```

97

98

## Void Method Stubbing

99

100

### Stubbing Void Methods

101

102

```java { .api }

103

@Deprecated

104

public static <T> VoidMethodStubbable<T> stubVoid(T mock);

105

```

106

107

**Modern approach using do-family:**

108

109

```java

110

// Void method that should throw exception

111

doThrow(new RuntimeException()).when(mock).clear();

112

113

// Void method that should do nothing (default behavior)

114

doNothing().when(mock).clear();

115

116

// Void method that should call real method (for spies)

117

doCallRealMethod().when(spy).clear();

118

```

119

120

## Custom Answers

121

122

Create complex stubbing behavior with custom logic:

123

124

```java { .api }

125

public interface Answer<T> {

126

T answer(InvocationOnMock invocation) throws Throwable;

127

}

128

129

public interface InvocationOnMock {

130

Object getMock();

131

Method getMethod();

132

Object[] getArguments();

133

<T> T getArgument(int index);

134

<T> T callRealMethod() throws Throwable;

135

}

136

```

137

138

**Usage Examples:**

139

140

```java

141

// Custom answer with argument access

142

when(mock.get(anyInt())).thenAnswer(new Answer<String>() {

143

public String answer(InvocationOnMock invocation) {

144

Object[] args = invocation.getArguments();

145

return "Element at index " + args[0];

146

}

147

});

148

149

// Lambda-based answer (Java 8+)

150

when(mock.get(anyInt())).thenAnswer(invocation -> {

151

int index = invocation.getArgument(0);

152

return "Element " + index;

153

});

154

155

// Answer that calls real method

156

when(spy.someMethod()).thenAnswer(invocation -> {

157

// Custom logic before

158

Object result = invocation.callRealMethod();

159

// Custom logic after

160

return result;

161

});

162

```

163

164

## Built-in Answers

165

166

Mockito provides several predefined answers:

167

168

```java { .api }

169

public class AdditionalAnswers {

170

public static <T> Answer<T> returnsFirstArg();

171

public static <T> Answer<T> returnsSecondArg();

172

public static <T> Answer<T> returnsLastArg();

173

public static <T> Answer<T> returnsArgAt(int position);

174

public static <T> Answer<T> delegatesTo(Object delegate);

175

}

176

```

177

178

**Usage Examples:**

179

180

```java

181

// Return first argument

182

when(mock.process(anyString())).then(returnsFirstArg());

183

184

// Return argument at specific position

185

when(mock.transform(anyString(), anyInt())).then(returnsArgAt(1));

186

187

// Delegate to real object

188

UserService realService = new UserService();

189

when(mock.process(anyString())).then(delegatesTo(realService));

190

```

191

192

## Argument Matching in Stubbing

193

194

Use argument matchers to create flexible stubs:

195

196

```java

197

// Exact matching

198

when(mock.get("key")).thenReturn("value");

199

200

// Argument matchers

201

when(mock.get(anyString())).thenReturn("default");

202

when(mock.process(eq("input"))).thenReturn("output");

203

when(mock.calculate(anyInt(), gt(10))).thenReturn(100);

204

205

// Custom matchers

206

when(mock.validate(argThat(s -> s.length() > 5))).thenReturn(true);

207

```

208

209

## Stubbing Best Practices

210

211

### Stub Only What You Need

212

213

```java

214

// Good - specific stubbing

215

when(userService.findById(123)).thenReturn(user);

216

217

// Avoid - overly broad stubbing

218

when(userService.findById(anyInt())).thenReturn(user);

219

```

220

221

### Use Appropriate Return Types

222

223

```java

224

// Good - match expected return type

225

when(mock.getUsers()).thenReturn(Arrays.asList(user1, user2));

226

227

// Avoid - mismatched types

228

when(mock.getUsers()).thenReturn(null); // Better to return empty list

229

```

230

231

### Handle Edge Cases

232

233

```java

234

// Good - handle null inputs

235

when(service.process(null)).thenThrow(IllegalArgumentException.class);

236

when(service.process(anyString())).thenReturn("processed");

237

238

// Good - handle different scenarios

239

when(service.save(any(User.class)))

240

.thenReturn(true) // First call succeeds

241

.thenReturn(false); // Second call fails

242

```

243

244

### Spy Stubbing Guidelines

245

246

```java

247

List<String> spy = spy(new ArrayList<>());

248

249

// WRONG - can cause issues with spies

250

when(spy.get(0)).thenReturn("stubbed");

251

252

// CORRECT - use do-family for spies

253

doReturn("stubbed").when(spy).get(0);

254

```

255

256

## Troubleshooting Common Issues

257

258

### UnfinishedStubbingException

259

260

```java

261

// WRONG - incomplete stubbing

262

when(mock.someMethod()); // Missing thenReturn/thenThrow

263

264

// CORRECT

265

when(mock.someMethod()).thenReturn("value");

266

```

267

268

### WrongTypeOfReturnValue

269

270

```java

271

// WRONG - return type mismatch

272

when(mock.size()).thenReturn("not a number");

273

274

// CORRECT

275

when(mock.size()).thenReturn(42);

276

```

277

278

### Stubbing Void Methods

279

280

```java

281

// WRONG - can't use when() with void methods

282

when(mock.clear()).thenReturn(something); // Compilation error

283

284

// CORRECT

285

doNothing().when(mock).clear();

286

doThrow(new RuntimeException()).when(mock).clear();

287

```