简体   繁体   中英

How to test Callable method which uses only operations from third-party library?

In call() method of Callable class, I have call third-party library to do iText related job. Now, I am planning to test this public method. However, I am a bit confused about what I should do. Should I not test this class because it does third-party related operations? If I should test acc. to Test driven methodology, how can I test this Callable method with third-party operations in it?

class Foo implements Callable<String> {
    @Override
    public String call(){
        PdfReader pdfReader = new PdfReader(filename);
        // do iText, external, library related jobs

        return (buffer);
    }
}

Instead of initializing the PdfReader inside call , create an instance field for it and initialize it through an argument passed to a constructor parameter.

private PdfReader pdfReader;
public Foo(PdfReader pdfReader) {
    this.pdfReader = pdfReader;
}

You can then mock the PdfReader and pass the mocked object in to the constructor. Set your expectations on the mock and verify them after call is invoked.

themIt's best not to use test doubles (eg mocks) for 3rd party objects. It's better to define an interface for it against which you can code in TDD fashion using test doubles, and then implement this interface in a thin layer that actually uses the 3rd party library and for which you can create integration tests.

Of course, you need to be sure you need a test double at all, meaning it's impossible to use the actual 3rd party library in the test (eg by reading a real PDF). Certainly in the case of reading PDFs, it shouldn't have side effects on other tests or subsequent runs of the same test anyway.

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