What is the easiest way to stub complex interface in Java?

My code accepts the interface as input, but only implements several interface methods (often, just getters).

When testing the code, I would like to define an anonymous inner class that returns test data. But what should I do with all the other methods that the interface requires?

I could use my IDE to automatically create a stub for the interface, but it looks pretty hard.

What is the easiest way to drown out the two methods that I care about and none of the methods that I do?

+3
source share
5 answers

If you use JUnit for testing, use Mocks instead of stubs.

"" Mocks Are not Stub"

EasyMock framework, . . , Fowler, unitils EasyMock, , . , , , EasyMock .

+5
+1

" " , .

class MyAdapter extends MyClass {
  public void A() {
  }
  ...
}
0

I believe that the classic way is to create an abstract class with empty methods. At least the way Sun did for MouseListener by creating a MouseAdapter to facilitate the use of these events.

0
source

EasyMock or JMock are definitely winners. I have not used JMock, but I know that with EasyMock you can configure the Mock object according to the test script, and it will return certain values ​​in certain situations or points during the test. It is quite easy to learn and get started, usually in less than an hour.

0
source

Source: https://habr.com/ru/post/1697134/


All Articles