85 lines
2.3 KiB
Plaintext
85 lines
2.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
JUnit assertions should not be made from the `run` method of a `Runnable`, because their failure may not be detected in the test that initiated them.
|
|
Failed assertions throw assertion errors.
|
|
However, if the error is thrown from another thread than the one that initiated the test, the thread will exit but the test will not fail.
|
|
|
|
|
|
|
|
|
|
== How to fix it
|
|
Assertions in `Runnable` tasks should be extracted or executed by the main thread to make the whole test fail.
|
|
|
|
=== Code examples
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
class RunnableWithAnAssertion extends Thread {
|
|
@Override
|
|
public void run() {
|
|
Assert.assertEquals(expected, actual); // Noncompliant
|
|
}
|
|
|
|
@Test
|
|
void test() {
|
|
RunnableWithAnAssertion otherThread = new RunnableWithAnAssertion();
|
|
otherThread.start(); // The assertion in the run method above will be executed by other thread than the current one
|
|
// ...
|
|
// Perform some actions that do not make the test fail
|
|
// ...
|
|
Assert.assertTrue(true);
|
|
}
|
|
}
|
|
----
|
|
==== Compliant solution
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
class RunnableWithAnAssertion extends Thread {
|
|
@Override
|
|
public void run() {
|
|
Assert.assertEquals(expected, actual); // Noncompliant
|
|
}
|
|
|
|
@Test
|
|
void test() {
|
|
RunnableWithAnAssertion otherThread = new RunnableWithAnAssertion();
|
|
otherThread.run();
|
|
// ...
|
|
// The failed assertions in the run method will prevent us from reaching the assertion below
|
|
// ...
|
|
Assert.assertTrue(true);
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove this assertion.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 22 Oct 2014, 19:20:32 Ann Campbell wrote:
|
|
Note that Applicability is marked only for Tests
|
|
|
|
=== on 24 Nov 2014, 19:33:09 Nicolas Peru wrote:
|
|
I am guessing here and so the answer should probably part of the RSPEC : The run method is a run method of a Thread class ?
|
|
|
|
=== on 22 Apr 2015, 11:01:15 Ann Campbell wrote:
|
|
Since you're already implementing this [~nicolas.peru], I'm guessing it's okay.
|
|
|
|
=== on 22 Apr 2015, 11:20:20 Nicolas Peru wrote:
|
|
\[~ann.campbell.2]yes, more especially with the the mention of ``++Runnable++``
|
|
|
|
endif::env-github,rspecator-view[]
|