简体   繁体   中英

how do I test anonymous class?

There are few legacy code that uses anonymous class and it ends up being majority of code in a single file. I was wondering if there are anyway to test anonymous class?

for example:

if (wp.speed != null && wp.speed >= 0) {

            FlightProtocol fp = new FlightProtocol() { //starts here

                @Override
                public Query getQuery() {
                    Query q = Query.empty();
                    if (wp.minSpeed < 0)
                        q = Query.and(q, Query.eq(Speed.Function, WayPoint));
                    else {
                        q = Query.and(q, Query.eq(Speed.Function, Field));
                        q = Query.and(q, Query.eq(Speed.Calc, wp.maxSpeed-wp.minSpeed));
                    }
                    q = Query.and(q, Query.eq(Speed.Id, wp.altitude/greatCircle));
                    return q;
                }
} else { ...}

So something like this or similar can even be unit tested?

The intent with unit tests is to verify the behavior of the public API. An anonymous class is an implementation detail, and writing unit tests to verify how it works (directly) will make your tests brittle. Instead write tests that verify the code that calls your anonymous class.

If the behavior of your anonymous class is so complex you want to test it in isolation, it shouldn't be anonymous. Extract it into its own class (likely as a package-private static inner class) then you can test it as normal.

You cannot test an anonymous class directly. You should either refactor your anonymous class such that it is not anonymous or just test the public API of the containing class.

The same is true of lambda expressions. If you want to be able to unit test your functionality you cannot define that functionality inline.

Why you have to test inner class?

To be sure behaviour is the expected test the outter class or method.

Just use the class as is and test if behaviour of the outer class / method is the expected. You don't need to test the inner class to ensure it's correct behaviour.

Great add-on from dimo414 's comment.

You shouldn't need to test the inner class . It's entirely possible for an inner class to have overly-complex behavior, at which point it should be pulled out into its own code block and tested like any other code .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM