How to check NetBeans platform code that uses Lookups?

TL DR How do I write unit tests for NetBeans platform code that uses static methods to look for dependencies?

In a NetBeans platform application, I find the code as follows:

MyService service = Lookup.getDefault().lookup(MyService.class);
service.doStuff(....);

To me, static access seems antipattern and hard to test. When I'm around Google, I find only comments about low grip and high grip, TV interfaces, etc.

Many people seem to think this is a good idea , but I wonder how I can write a reasonable unit test for code like this without resorting to mocking static methods or using the Lookup function in my unit test.

The first idea that comes to my mind is to refactor the search as a regular dependency:

public class MyClass {

   private Lookup lookup = Lookup.getDefault();

   public void myMethod() {
       MyService service = lookup.lookup(MyService .class);
       service.doStuff(....);
   }

   public void setLookup(Lookup lookup) {
       this.lookup = lookup;
   }

, .

, Lookup.getDefault() . , Netbeans, , , .

, - . Netbeans?

+4
2

.

1 - Lookup

@org.openide.util.lookup.ServiceProvider(service = MyService.class, position = 1)
public class TestService implements MyService {
    public void doStuff(....) {

2 - NBJunit MockService

public class MyTest extends NbTestCase {
    public void setUp() throws Exception {     
        org.netbeans.junit.MockServices.setServices(TestService.class);
    }

3 :

static {
    System.setProperty("org.openide.util.Lookup", TestLookup.class.getName());
}

public class TestLookup extends org.openide.util.lookup.AbstractLookup {
    public TestLookup() {
        this(new org.openide.util.lookup.InstanceContent());
    }

    private TestLookup(org.openide.util.lookup.InstanceContent ic) { 
        super(ic);
        ic.add(new TestService());
    }

: https://openide.netbeans.org/tutorial/test-patterns.html.

+3

TestService ( , Lookup , ).

TestService .

0

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


All Articles