File: DoNotMockAutoValue.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (56 lines) | stat: -rw-r--r-- 1,602 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
`@AutoValue` is used to represent pure data classes. Mocking these should not be
necessary: prefer constructing them in the same way production code would.

To make the argument another way: the fact that `AutoValue` classes are not
`final` is an implementation detail of the way they're generated. They should be
regarded as logically final insofar as they must not be extended by
non-generated code. If they were final, they also would not be mockable.

Instead of mocking:

```java
@Test
public void test() {
  MyAutoValue myAutoValue = mock(MyAutoValue.class);
  when(myAutoValue.getFoo()).thenReturn("foo");
}
```

Prefer simply constructing an instance:

```java
@Test
public void test() {
  MyAutoValue myAutoValue = MyAutoValue.create("foo");
}
```

If your `AutoValue` has multiple required fields, and only one is relevant for a
test, consider using a [builder] or [`with`-style methods][wither] to create
test instances with just the fields you care about. Consider using

[builder]: https://github.com/google/auto/blob/master/value/userguide/builders.md
[wither]: https://github.com/google/auto/blob/master/value/userguide/builders-howto.md#withers

```java
private MyAutoValue.Builder myAutoValueBuilder() {
  return MyAutoValue.builder().bar(42).baz(false);
}

@Test
public void test() {
  MyAutoValue myAutoValue = myAutoValueBuilder.foo("foo").build();
}
```

or:

```java
private static final MyAutoValue MY_AUTO_VALUE =
    MyAutoValue.create(/* foo= */ "", /* bar= */ 42, /* baz= */ false);

@Test
public void test() {
  MyAutoValue myAutoValue = MY_AUTO_VALUE.withFoo("foo");
}
```