diff --git a/.idea/compiler.xml b/.idea/compiler.xml index a21886d..a4e4821 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -8,6 +8,7 @@ + @@ -17,6 +18,7 @@ + diff --git a/.idea/encodings.xml b/.idea/encodings.xml index 401bd49..301d3cb 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -3,6 +3,7 @@ + diff --git a/.idea/modules.xml b/.idea/modules.xml index eaea7cb..a7fee14 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -3,6 +3,7 @@ + diff --git a/.travis.yml b/.travis.yml index 0ac38d7..2ec4489 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,6 @@ language: java jdk: - oraclejdk8 - oraclejdk9 - - oraclejdk10 - openjdk8 - openjdk9 - openjdk10 diff --git a/exception-test-base/CHANGELOG.md b/exception-test-base/CHANGELOG.md new file mode 100644 index 0000000..645a8ef --- /dev/null +++ b/exception-test-base/CHANGELOG.md @@ -0,0 +1,5 @@ +# CHANGELOG + +## eu.coldrye.junit:exception-test-base:1.0.0 + +- feature(#56): initial version diff --git a/exception-test-base/LICENSE b/exception-test-base/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/exception-test-base/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. diff --git a/exception-test-base/README.md b/exception-test-base/README.md new file mode 100644 index 0000000..09cbae3 --- /dev/null +++ b/exception-test-base/README.md @@ -0,0 +1,43 @@ +# enum-test-base + +A simple base class for all your enum testing needs. + +The default behaviour of the base class is to make sure that you have 100% test coverage on all of your standard enums. + +More complex usage scenarios where you have additional behaviour and properties in your enums are also be supported, +including nested test classes. + + +## Usage + + +### Maven + +```xml + + eu.coldrye.junit + enum-test-base + 1.0.0 + test + +``` + + +### Examples + +```java +package org.example; + +import eu.coldrye.junit.bases.AbstractEnumTestBase; + +public class SampleEnumTest extends AbstractEnumTestBase { + + // done, 100% coverage +} +``` + + +## References + +- [GitHub](https://github.com/coldrye-java/junit-testing/tree/master/enum-test-base) +- [Sonar](http://sonar.coldrye.eu/dashboard?id=eu.coldrye.junit%3Aenum-test-base) diff --git a/exception-test-base/exception-test-base.iml b/exception-test-base/exception-test-base.iml new file mode 100644 index 0000000..f9b0df9 --- /dev/null +++ b/exception-test-base/exception-test-base.iml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exception-test-base/pom.xml b/exception-test-base/pom.xml new file mode 100644 index 0000000..7df0dba --- /dev/null +++ b/exception-test-base/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + eu.coldrye.junit + junit-testing + 1.3-SNAPSHOT + + + exception-test-base + ${project.groupId}:${project.artifactId} + 1.0.0-SNAPSHOT + + + 1.2.1-SNAPSHOT + + + + + eu.coldrye.junit + junit-common + ${junit-common.version} + compile + + + diff --git a/exception-test-base/src/main/java/eu/coldrye/junit/bases/AbstractThrowableTestBase.java b/exception-test-base/src/main/java/eu/coldrye/junit/bases/AbstractThrowableTestBase.java new file mode 100644 index 0000000..8e9fd5b --- /dev/null +++ b/exception-test-base/src/main/java/eu/coldrye/junit/bases/AbstractThrowableTestBase.java @@ -0,0 +1,240 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases; + +import eu.coldrye.junit.util.GenericTypeParameterResolver; +import eu.coldrye.junit.util.ReflectionUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Optional; +import java.util.function.Supplier; + +/** + * @param + */ +public abstract class AbstractThrowableTestBase { + + /** + * This test is included for the purpose of getting full coverage for the default constructor, if it exists. + *

+ * This will look for a constructor with no formal parameters. + */ + @Test + public void ensureFullCoverageForDefaultConstructor() throws Exception { + + Constructor ctor = ReflectionUtils.resolveConstructor(getThrowableClass()); + if (ctor != null) { + + runConstructorAssertions(null, null, null, "standard default constructor"); + } + } + + /** + * This test is included for the purpose of getting full coverage for the default message only constructor, if it + * exists. + *

+ * This will look for a constructor with a single formal parameter of type {@code String}. + */ + @Test + public void ensureFullCoverageForStandardConstructorWithMessage() throws Exception { + + Constructor ctor = ReflectionUtils.resolveConstructor(getThrowableClass(), false, String.class); + if (ctor != null) { + + runConstructorAssertions( + () -> new Object[]{"testing"}, + () -> new Class[]{String.class}, + () -> new ThrowableAssertion[]{ + + (instance, parameters, parameterTypes) -> Assertions.assertNotNull(instance), + (instance, parameters, parameterTypes) -> + Assertions.assertTrue(getThrowableClass().isAssignableFrom(instance.getClass())), + (instance, parameters, parameterTypes) -> + Assertions.assertEquals(parameters[0], instance.getMessage(), "message"), + }, + "standard message constructor" + ); + } + } + + /** + * This test is included for the purpose of getting full coverage for the default message and cause constructor, if + * it exists. + *

+ * This will look for a constructor with a two formal parameter of type {@code String} and {@code Throwable}. + */ + @Test + public void ensureFullCoverageForStandardConstructorWithMessageAndCause() throws Exception { + + Constructor ctor = ReflectionUtils.resolveConstructor(getThrowableClass(), false, String.class, Throwable.class); + if (ctor != null) { + + Class parameterType = ReflectionUtils.getFormalParameterType(ctor, 1); + runConstructorAssertions( + () -> new Object[]{"testing", constructCauseFromFormalParameterType(parameterType)}, + () -> new Class[]{String.class, parameterType}, + () -> new ThrowableAssertion[]{ + + (instance, parameters, parameterTypes) -> + Assertions.assertTrue(parameters[1] != null + || parameterTypes[1].isAssignableFrom(instance.getCause().getClass()), "causeType"), + (instance, parameters, parameterTypes) -> + Assertions.assertEquals(parameters[0], instance.getMessage(), "message"), + (instance, parameters, parameterTypes) -> + Assertions.assertTrue(parameters[1] == null + || ((Throwable) parameters[1]).getMessage().equals(instance.getCause().getMessage()), "cause#message") + }, + "standard message and cause constructor" + ); + } + } + + /** + * This test is included for the purpose of getting full coverage for the default cause only constructor, if it + * exists. + *

+ * This will look for a constructor with a single formal parameter of type {@code Throwable}. + */ + @Test + public void ensureFullCoverageForStandardConstructorWithCause() throws Exception { + + Constructor ctor = ReflectionUtils.resolveConstructor(getThrowableClass(), false, Throwable.class); + if (ctor != null) { + + Class parameterType = ReflectionUtils.getFormalParameterType(ctor, 0); + runConstructorAssertions( + () -> new Object[]{constructCauseFromFormalParameterType(parameterType)}, + () -> new Class[]{parameterType}, + () -> new ThrowableAssertion[]{ + + (instance, parameters, parameterTypes) -> + Assertions.assertTrue( + parameterTypes[0].isAssignableFrom(instance.getCause().getClass()), "causeType"), + (instance, parameters, parameterTypes) -> + Assertions.assertEquals( + ((Throwable) parameters[0]).getMessage(), instance.getCause().getMessage(), "cause#message") + }, + "standard cause only constructor" + ); + } + } + + @SuppressWarnings("unchecked") + protected final Class getThrowableClass() { + + return (Class) GenericTypeParameterResolver.resolve(this, AbstractThrowableTestBase.class, 0); + } + + protected final void runConstructorAssertions(ParameterSupplier parameterSupplier, + ParameterTypesSupplier parameterTypesSupplier, + ThrowableAssertionsSupplier throwableAssertionsSupplier, + String message) throws Exception { + + Class clazz = getThrowableClass(); + try { + + Class[] parameterTypes = Optional.ofNullable(parameterTypesSupplier).orElse(() -> new Class[]{}).get(); + Constructor ctor = ReflectionUtils.resolveConstructor(clazz, false, parameterTypes); + if (ctor != null) { + + Object[] parameters = Optional.ofNullable(parameterSupplier).orElse(() -> new Object[]{}).get(); + ThrowableAssertion[] throwableAssertions = + Optional.ofNullable(throwableAssertionsSupplier).orElse(() -> new ThrowableAssertion[]{}).get(); + + ReflectionUtils.makeAccessible(ctor); + T instance = ctor.newInstance(parameters); + Executable[] executables = new Executable[throwableAssertions.length + 2]; + + executables[0] = () -> Assertions.assertNotNull(instance); + executables[1] = () -> Assertions.assertTrue(getThrowableClass().isAssignableFrom(instance.getClass())); + + int index = 2; + for (ThrowableAssertion throwableAssertion : throwableAssertions) { + + executables[index++] = () -> throwableAssertion.apply(instance, parameters, parameterTypes); + } + + Assertions.assertAll(executables); + } + } catch (IllegalAccessException | InstantiationException | InvocationTargetException ex) { + + Assertions.fail(message + " of throwable " + clazz.getCanonicalName() + " failed.", ex); + } + } + + private Throwable constructCauseFromFormalParameterType(Class parameterType) throws Exception { + + Throwable result = null; + if (Throwable.class.isAssignableFrom(parameterType)) { + + // try for default constructor first + Constructor ctor = ReflectionUtils.resolveConstructor(parameterType, true); + if (ctor != null) { + + result = (Throwable) ctor.newInstance(); + } else { + + // try for default message only ctor next + ctor = ReflectionUtils.resolveConstructor(parameterType, true, String.class); + + if (ctor != null) { + + result = (Throwable) ctor.newInstance("testing"); + } + /* and we will not do this, the user must implement his or her own test cases for that + else { + + // try for default cause only ctor next (recursively) + } + */ + } + } + + return result; + } + + @FunctionalInterface + protected interface ThrowableAssertionsSupplier extends Supplier { + + } + + @FunctionalInterface + protected interface ParameterTypesSupplier extends Supplier[]> { + + } + + @FunctionalInterface + protected interface ThrowingSupplier { + + T get() throws Exception; + } + + @FunctionalInterface + protected interface ParameterSupplier extends ThrowingSupplier { + + } + + @FunctionalInterface + protected interface ThrowableAssertion { + + void apply(Throwable instance, Object[] parameters, Class[] parameterTypes) throws Exception; + } +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/CustomCauseOnlyCustomThrowableTest.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/CustomCauseOnlyCustomThrowableTest.java new file mode 100644 index 0000000..f37d86e --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/CustomCauseOnlyCustomThrowableTest.java @@ -0,0 +1,23 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases; + +import eu.coldrye.junit.bases.fixtures.CustomCauseOnlyCustomThrowable; + +public class CustomCauseOnlyCustomThrowableTest extends AbstractThrowableTestBase { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/DefaultConstructorOnlyCustomThrowableTest.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/DefaultConstructorOnlyCustomThrowableTest.java new file mode 100644 index 0000000..3e8680b --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/DefaultConstructorOnlyCustomThrowableTest.java @@ -0,0 +1,24 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases; + +import eu.coldrye.junit.bases.fixtures.DefaultConstructorOnlyCustomThrowable; + +public class DefaultConstructorOnlyCustomThrowableTest + extends AbstractThrowableTestBase { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/DefaultConstructorOnlyExceptionTest.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/DefaultConstructorOnlyExceptionTest.java new file mode 100644 index 0000000..fea31df --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/DefaultConstructorOnlyExceptionTest.java @@ -0,0 +1,23 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases; + +import eu.coldrye.junit.bases.fixtures.DefaultConstructorOnlyException; + +public class DefaultConstructorOnlyExceptionTest extends AbstractThrowableTestBase { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/FullFeaturedThrowableTest.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/FullFeaturedThrowableTest.java new file mode 100644 index 0000000..46d1adf --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/FullFeaturedThrowableTest.java @@ -0,0 +1,23 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases; + +import eu.coldrye.junit.bases.fixtures.FullFeaturedThrowable; + +public class FullFeaturedThrowableTest extends AbstractThrowableTestBase { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/MessageOnlyCustomThrowableTest.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/MessageOnlyCustomThrowableTest.java new file mode 100644 index 0000000..cf7b60b --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/MessageOnlyCustomThrowableTest.java @@ -0,0 +1,23 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases; + +import eu.coldrye.junit.bases.fixtures.MessageOnlyCustomThrowable; + +public class MessageOnlyCustomThrowableTest extends AbstractThrowableTestBase { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/CustomCauseOnlyCustomThrowable.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/CustomCauseOnlyCustomThrowable.java new file mode 100644 index 0000000..cd2dcd1 --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/CustomCauseOnlyCustomThrowable.java @@ -0,0 +1,25 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases.fixtures; + +public class CustomCauseOnlyCustomThrowable extends Throwable { + + public CustomCauseOnlyCustomThrowable(MessageOnlyCustomThrowable cause) { + + super(cause); + } +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/DefaultConstructorOnlyCustomThrowable.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/DefaultConstructorOnlyCustomThrowable.java new file mode 100644 index 0000000..1237fa3 --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/DefaultConstructorOnlyCustomThrowable.java @@ -0,0 +1,21 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases.fixtures; + +public class DefaultConstructorOnlyCustomThrowable extends Throwable { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/DefaultConstructorOnlyException.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/DefaultConstructorOnlyException.java new file mode 100644 index 0000000..a69d9ac --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/DefaultConstructorOnlyException.java @@ -0,0 +1,21 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases.fixtures; + +public class DefaultConstructorOnlyException extends Exception { + +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/FullFeaturedThrowable.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/FullFeaturedThrowable.java new file mode 100644 index 0000000..6813fd6 --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/FullFeaturedThrowable.java @@ -0,0 +1,40 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases.fixtures; + +public class FullFeaturedThrowable extends Throwable { + + public FullFeaturedThrowable() { + + super(); + } + + public FullFeaturedThrowable(String message) { + + super(message); + } + + public FullFeaturedThrowable(MessageOnlyCustomThrowable cause) { + + super(cause); + } + + public FullFeaturedThrowable(String message, MessageOnlyCustomThrowable cause) { + + super(message, cause); + } +} diff --git a/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/MessageOnlyCustomThrowable.java b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/MessageOnlyCustomThrowable.java new file mode 100644 index 0000000..ac38138 --- /dev/null +++ b/exception-test-base/src/test/java/eu/coldrye/junit/bases/fixtures/MessageOnlyCustomThrowable.java @@ -0,0 +1,25 @@ +/* + * Copyright 2018 coldrye.eu, Carsten Klein + * + * 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 + * + * http://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. + */ + +package eu.coldrye.junit.bases.fixtures; + +public class MessageOnlyCustomThrowable extends Throwable { + + public MessageOnlyCustomThrowable(String message) { + + super(message); + } +} diff --git a/junit-common/src/main/java/eu/coldrye/junit/util/ReflectionUtils.java b/junit-common/src/main/java/eu/coldrye/junit/util/ReflectionUtils.java index 84d6e7e..d9efc0d 100644 --- a/junit-common/src/main/java/eu/coldrye/junit/util/ReflectionUtils.java +++ b/junit-common/src/main/java/eu/coldrye/junit/util/ReflectionUtils.java @@ -19,7 +19,10 @@ import org.junit.platform.commons.util.Preconditions; import java.lang.annotation.Annotation; +import java.lang.reflect.AccessibleObject; import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Constructor; +import java.lang.reflect.Executable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayDeque; @@ -36,6 +39,11 @@ */ public final class ReflectionUtils { + // must not be instantiated + private ReflectionUtils() { + + } + /** * Gets the specified annotations from all interfaces implemented by and super classes of the specified class clazz. * @@ -54,23 +62,31 @@ public static List getAllAnnotations(Class clazz, Class> todo = new ArrayDeque<>(); todo.push(clazz); while (!todo.isEmpty()) { + Class annotated = todo.pop(); for (Class annotationClass : annotationClasses) { + if (annotated.isAnnotationPresent(annotationClass)) { + result.add(annotated.getAnnotation(annotationClass)); } } + Class[] ifaces = annotated.getInterfaces(); if (ifaces.length > 0) { + todo.addAll(Arrays.asList(ifaces)); } if (!annotated.isInterface()) { + Class superClass = annotated.getSuperclass(); if (!Objects.isNull(superClass)) { + todo.push(superClass); } } } + return result; } @@ -84,16 +100,23 @@ public static boolean isAnnotatedBy(AnnotatedElement annotated, Class requested : annotationClasses) { + Class type = annotation.annotationType(); if (type.equals(requested) || type.isAnnotationPresent(requested)) { - return true; + + result = true; + break; } } } - return false; + + return result; } public static boolean isAnnotatedBy(AnnotatedElement annotated, String annotationName) { @@ -126,15 +149,20 @@ public static List getDeclaredFields(Class clazz, Class current = clazz; while (true) { + Field[] declaredFields = current.getDeclaredFields(); for (Field field : declaredFields) { + if (ReflectionUtils.isAnnotatedBy(field, annotationClasses)) { + result.add(field); } } current = current.getSuperclass(); + // we must break on Object.class if ((Object.class.equals(current))) { + break; } } @@ -154,14 +182,21 @@ public static Method findMethod(Class clazz, String name, Class... paramet Preconditions.notNull(clazz, "clazz must not be null"); // NOSONAR Preconditions.notBlank(name, "name must not be blank"); // NOSONAR + Method result = null; + Class current = clazz; while (true) { + Method method = ReflectionUtils.findMethod0(current, name, true, parameterTypes); if (!Objects.isNull(method) || Object.class.equals(current)) { - return method; + + result = method; + break; } current = current.getSuperclass(); } + + return result; } public static Method findMethod(String className, String methodName) { @@ -209,14 +244,19 @@ public static String setterName(Field field) { */ private static Method findMethod0(Class clazz, String name, boolean matchParameters, Class... parameterTypes) { + Method result = null; + for (Method method : clazz.getDeclaredMethods()) { - if (method.getName().equals(name) && (!matchParameters - || (parameterTypes.length > 0 && Arrays.equals(method.getParameterTypes(), parameterTypes)))) { - return method; + if (method.getName().equals(name) + && (!matchParameters || (formalAndRequiredParameterTypesMatch(matchParameters, method.getParameterTypes(), parameterTypes)))) { + + result = method; + break; } } - return null; + + return result; } public static boolean hasEnclosingInstance(Object instance) { @@ -226,6 +266,8 @@ public static boolean hasEnclosingInstance(Object instance) { public static Object getEnclosingInstance(Object instance) { + Object result = null; + if (hasEnclosingInstance(instance)) { try { @@ -233,18 +275,76 @@ public static Object getEnclosingInstance(Object instance) { Field field = instance.getClass().getDeclaredField("this$0"); field.setAccessible(true); - return field.get(instance); - } catch (IllegalAccessException|NoSuchFieldException ex) { + result = field.get(instance); + } catch (IllegalAccessException | NoSuchFieldException ex) { // ignore } } - return null; + return result; } - // must not be instantiated - private ReflectionUtils() { + public static Constructor resolveConstructor(Class clazz, Class... parameterTypes) { + + return resolveConstructor(clazz, true, parameterTypes); + } + + @SuppressWarnings("unchecked") + public static Constructor resolveConstructor(Class clazz, boolean strict, Class... parameterTypes) { + + Constructor result = null; + + for (Constructor ctor : clazz.getConstructors()) { + + if (formalAndRequiredParameterTypesMatch(strict, ctor.getParameterTypes(), parameterTypes)) { + + result = (Constructor) ctor; + break; + } + } + + return result; + } + + public static boolean formalAndRequiredParameterTypesMatch(boolean strict, Class[] formalParameterTypes, Class[] requiredParameterTypes) { + + boolean result = false; + + // the default constructor + if (formalParameterTypes.length == 0 && requiredParameterTypes.length == 0) { + + result = true; + } else if (formalParameterTypes.length == requiredParameterTypes.length) { + + result = true; + for (int index = 0; index < formalParameterTypes.length; index++) { + + Class formalParameterType = formalParameterTypes[index]; + Class requiredParameterType = requiredParameterTypes[index]; + + if (formalParameterType != requiredParameterType) { + + if (strict && !formalParameterType.isAssignableFrom(requiredParameterType) + || !strict && !requiredParameterType.isAssignableFrom(formalParameterType)) { + + result = false; + break; + } + } + } + } + + return result; + } + + public static void makeAccessible(AccessibleObject accessibleObject) { + + accessibleObject.setAccessible(true); + } + + public static Class getFormalParameterType(Executable executable, int index) { + return executable.getParameters()[index].getType(); } } diff --git a/junit-common/src/test/java/eu/coldrye/junit/util/ReflectionUtilsTest.java b/junit-common/src/test/java/eu/coldrye/junit/util/ReflectionUtilsTest.java index 7f3c8bf..f45559c 100644 --- a/junit-common/src/test/java/eu/coldrye/junit/util/ReflectionUtilsTest.java +++ b/junit-common/src/test/java/eu/coldrye/junit/util/ReflectionUtilsTest.java @@ -104,6 +104,30 @@ public void setterNameMustReturnTheExpectedName() throws Exception { Assertions.assertEquals("setCustom", ReflectionUtils.setterName(field)); } + @Test + public void makeAccessible() { + + Assertions.fail("not implemented yet"); + } + + @Test + public void getFormalParameterType() { + + Assertions.fail("not implemented yet"); + } + + @Test + public void formalAndRequiredParameterTypesMatch() { + + Assertions.fail("not implemented yet"); + } + + @Test + public void resolveConstructor() { + + Assertions.fail("not implemented yet"); + } + // @Test // public void resolveMethodMustResolveExpectedMethod() { // diff --git a/pom.xml b/pom.xml index 452e7ea..7a8c42c 100644 --- a/pom.xml +++ b/pom.xml @@ -39,6 +39,7 @@ junit-common enum-test-base + exception-test-base junit-testing-common junit-env-extension junit-env-hadoop-mini-clusters