简体   繁体   中英

Mockito: mocking a method call of a generic typed class

I'm trying to mock a class derived from an Apache Beam generic class, and call a method of it using Mockito.

This is my real class:

    public class MyClass extends DoFn<Entity, TableRow> {

        public void processElement(ProcessContext c) {

            // some business logic

            c.output(new TableRow()) // c.output received a type defined in the derived class
        }
    }

And this is the test with the required mock:

DoFn<Entity, TableRow>.ProcessContext testContext = (DoFn<Entity, TableRow>.ProcessContext)mock(DoFn.ProcessContext.class);

when(textContext.output(any(TableRow.class))).thenReturn(42);

For some reason, I'm getting an error doing so, on the second line. That's the error:

Required type:
T

Provided:
void

reason: no instance(s) of type variable(s) T exist so that void conforms to T

Any solution for this? Thanks!

An acceptable answer seems to be found in the comments, but I would also in general advise against writing tests by mocking out Beam DoFns and the like. Instead, the recommendation would be to either factor out the code in the body of the DoFn into something that can be more directly tested (if it's non-trivial) or, preferably, use the DoFn(s) in an actual pipeline and assert that it produces the correct results (see https://beam.apache.org/documentation/pipelines/test-your-pipeline/ ).

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