Git Product home page Git Product logo

Comments (5)

hankem avatar hankem commented on September 25, 2024 3

Even if the ArchUnit library does not yet provide a fluent API for methods, you can still implement ClassesTransformers, DescribedPredicates and ArchConditions in your own code, e.g.:

import java.util.*;
import com.tngtech.archunit.base.*;
import com.tngtech.archunit.core.domain.*;
import com.tngtech.archunit.core.domain.properties.HasModifiers;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.*;
import static com.tngtech.archunit.core.domain.Formatters.formatLocation;
import static com.tngtech.archunit.core.domain.JavaModifier.PUBLIC;
import static com.tngtech.archunit.core.domain.properties.HasModifiers.Predicates.modifier;
import static com.tngtech.archunit.lang.Priority.MEDIUM;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.priority;

public class MethodReturnTypeTest {

    @ArchTest
    public static ArchRule all_public_methods_in_the_controller_layer_should_return_API_response_wrappers = priority(MEDIUM)
            .all(methods().that(areInPackage(PackageMatcher.of("ABC"))))
            .that(arePublic())
            .should(returnType(ApiWrapper.class))
            .because("we don't want to couple the client code directly to the API reponse classes");

    static ClassesTransformer<JavaMethod> methods() {
        return new AbstractClassesTransformer<JavaMethod>("methods") {
            @Override
            public Iterable<JavaMethod> doTransform(JavaClasses javaClasses) {
                List<JavaMethod> methods = new ArrayList<>();
                for (JavaClass javaClass : javaClasses) {
                    methods.addAll(javaClass.getMethods());
                }
                return methods;
            }
        };
    }

    static DescribedPredicate<JavaMember> areInPackage(PackageMatcher packageMatcher) {
        return new DescribedPredicate<JavaMember>("are in " + packageMatcher) {
            @Override
            public boolean apply(JavaMember member) {
                return packageMatcher.matches(member.getOwner().getPackage());
            }
        };
    }

    static DescribedPredicate<HasModifiers> arePublic() {
        return modifier(PUBLIC).as("are public");
    }

    static ArchCondition<JavaMethod> returnType(Class<?> type) {
        return new ArchCondition<JavaMethod>("return type " + type.getName()) {
            @Override
            public void check(JavaMethod method, ConditionEvents events) {
                boolean typeMatches = method.getReturnType().isAssignableTo(type);
                String message = method.getFullName() + " returns " + method.getReturnType().getName() + " " + formatLocation(method.getOwner(), 1);
                events.add(new SimpleConditionEvent(method, typeMatches, message));
            }
        };
    }
}

(PackageMatcher currently doesn't provide an accessor for packageIdentifier, so the areInPackage predicate uses its toString() representation...)

from archunit.

mlenkeit avatar mlenkeit commented on September 25, 2024

Just found #38, must have missed it before, sorry for that. Feel free to close this issue if you see it as a duplicate and you'd like to continue the discussion there.

from archunit.

codecholeric avatar codecholeric commented on September 25, 2024

Thanks @mlenkeit for bringing that up! I think this is indeed covered by #38 and following
Also thanks @hankem for already providing an implementation to check this 😃
My only comment would be, that you can skip the priority(..) part and write the "areInPackage" even a little bit shorter with existing predicates:

ArchRuleDefinition.all(methods()).that(areDefinedInAPackage("..specific.."))
    .and(arePublic())
    .should(returnType(ApiWrapper.class))
    .because("we don't want to couple the client code directly to the API response classes");

// HasOwner.Functions.Get.<JavaClass>owner().is(JavaClass.Predicates.resideInAPackage(pkg));
static DescribedPredicate<? super JavaMember> areDefinedInAPackage(final String pkg) {
    return Get.<JavaClass>owner().is(resideInAPackage(pkg));
}

But I guess the gist is, yes, you can already assert what you want, but it is not yet as convenient, as it will be in the future 😉
Is this good enough for now? Because then I would close this issue, since this type of assertion will be covered in #38 and following, it's just a matter of priority (like "you can test it, but it's not as convenient as it should be" versus "it doesn't work at all" like Java 9 support was)
What we could do for now though, is to add exactly this example to ArchUnit-Examples, so someone else looking for it might find it. (then with #38 ff we could use exactly this example to verify, that the new API feels good)

from archunit.

mlenkeit avatar mlenkeit commented on September 25, 2024

@hankem wow, this is a great example! When I thought about it again, I was thinking about somehow combining ArchUnit with the Reflection API to achieve this. But your example, which is only using ArchUnit APIs, is obviously much clearer and more concise. Thank you so much for sharing!

@codecholeric I think that's definitely good enough for now, feel free to close the issue. Adding this to the ArchUnit-Examples might indeed be helpful, great idea!

I'll also subscribe to #38 to stay up-to-date.

This is a great project btw, keep up the good work!

from archunit.

codecholeric avatar codecholeric commented on September 25, 2024

Thanks, glad you like it 😄
I'll close this issue later with an PR to :archunit-examples then (and immediately add it to the released ArchUnit-Examples as well)

from archunit.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.