Skip to content

Commit

Permalink
Polish "Check that JUnit 5 test classes are package-private"
Browse files Browse the repository at this point in the history
 - Clear the new fields each time a new tree is begun. This prevents
   state from one tree affecting the checking of another.
 - Allow abstract test classes to be public

Closes gh-281
  • Loading branch information
wilkinsona committed Jul 26, 2024
1 parent 09679cc commit ab2ecf7
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,11 @@ public int[] getAcceptableTokens() {

@Override
public void beginTree(DetailAST rootAST) {
this.testClass = null;
this.imports.clear();
this.testMethods.clear();
this.lifecycleMethods.clear();
this.nestedTestClasses.clear();
}

@Override
Expand Down Expand Up @@ -181,7 +183,7 @@ private boolean shouldCheck() {
}

private void check() {
if (this.testClass != null) {
if (this.testClass != null && !isAbstract(this.testClass)) {
checkVisibility(Arrays.asList(this.testClass), "junit5.publicClass", null);
}
checkVisibility(this.nestedTestClasses, "junit5.publicNestedClass", "junit5.privateNestedClass");
Expand All @@ -200,6 +202,11 @@ private void check() {
checkVisibility(this.lifecycleMethods, "junit5.lifecyclePublicMethod", "junit5.lifecyclePrivateMethod");
}

private boolean isAbstract(DetailAST ast) {
DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
return modifiers.findFirstToken(TokenTypes.ABSTRACT) != null;
}

private void checkVisibility(List<DetailAST> asts, String publicMessageKey, String privateMessageKey) {
for (DetailAST ast : asts) {
DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
+0 errors
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2017-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import org.junit.jupiter.api.Test;

/**
* This is a valid example. We allow abstract test classes to be
* public so that classes in other packages can extend them.
*
* @author Andy Wilkinson
*/
public abstract class JUnit5PublicAbstractIsValid {

@Test
void doSomethingWorks() {
// test here
}

}

0 comments on commit ab2ecf7

Please sign in to comment.