If you need to unit test classes in a netbeans module and the classes use the Lookup.getDefault()
to “lookup” things that you want to mock you probably wonder how you can place the mock objects in the default Lookup
Adding objects to the Netbeans’s default Lookup
is relatively simple. Here is the answer:
-
Replace the `Lookup` instance returned by the `Lookup.getDefault()`
by defining a new entry in `META-INF/services`.
It’s just a matter of adding a file named
org.openide.util.Lookup$Provider
in theMETA-INF/services
folder inside your Unit Test source folder. That file should contain the fully qualified class name of your ownLookup.Provider
implementation. In my case the file contain just the stringcom.rubenlaguna.en4j.searchlucene.NoteFinderLuceneImplTest
because the test class itself implementsLookup.Provider
.By adding this to
META-INF/services
you’re actually forcingLookup.getLookup()
to use yourLookup.Provider
to obtain theLookup
instance that will be returned -
Create you own `Lookup.Provider`. You can even let your test class implement `Lookup.Provider` if you only have one test class.
In this example you can see that I inject a NoteRepository.class into the default lookup.