rspec/rules/S5969/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

98 lines
1.7 KiB
Plaintext

== Why is this an issue?
If you end up mocking every non-private method of a class in order to write tests, it is a strong sign that your test became too complex, or that you misunderstood the way you are supposed to use the mocking mechanism.
You should either refactor the test code into multiple units, or consider using the class itself, by either directly instantiating it, or creating a new one inheriting from it, with the expected behavior.
This rule reports an issue when every member of a given class are mocked.
=== Noncompliant code example
[source,java]
----
@Test
void test_requiring_MyClass() {
MyClass myClassMock = mock(MyClass.class); // Noncompliant
when(myClassMock.f()).thenReturn(1);
when(myClassMock.g()).thenReturn(2);
//...
}
abstract class MyClass {
abstract int f();
abstract int g();
}
----
=== Compliant solution
[source,java]
----
@Test
void test_requiring_MyClass() {
MyClass myClass = new MyClassForTest();
//...
}
class MyClassForTest extends MyClass {
@Override
int f() {
return 1;
}
@Override
int g() {
return 2;
}
}
----
or
[source,java]
----
@Test
void test_requiring_f() {
MyClass myClassMock = mock(MyClass.class);
when(myClassMock.f()).thenReturn(1);
//...
}
@Test
void test_requiring_g() {
MyClass myClassMock = mock(MyClass.class);
when(myClassMock.g()).thenReturn(2);
//...
}
abstract class MyClass {
abstract int f();
abstract int g();
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Refactor this test instead of mocking every non-private member of this class.
=== Highlighting
Primary location: mock variable declaration.
Secondaries: mocked methods.
endif::env-github,rspecator-view[]