Writing Tests For DataObjects and DataLoaders

Quite easy. At least in NetBeans 6.5 and newer. Everything shall work as declarative MIME resolvers are loaded automatically from unit tests and loaders are available from unit tests automatically.

Example code is below:

    private static final String BAD_MANIFEST_CONTENT =
            "Manifest-Version: 1.0\n" +
            "junk junk junk\n" +
            "some more junk\n";
    private static final String GOOD_MANIFEST_CONTENT =
            "Manifest-Version: 1.0\n" +
            "Java-Bean: true\n" +

    @Test public void checkContent() throws Exception {
        FileSystem fs = FileUtil.createMemoryFileSystem();
        FileObject good = fs.getRoot().createData("");
        writeFile(GOOD_MANIFEST_CONTENT, good);
        DataObject goodDob = DataObject.find(good);

        FileObject bad = fs.getRoot().createData("");
        writeFile(BAD_MANIFEST_CONTENT, bad);
        DataObject badDob = DataObject.find(bad);

        YourInterface y = goodDob.getLookup().lookup(YourInterface.class);

    private void writeFile(String content, FileObject file) throws Exception {
        OutputStream os = file.getOutputStream();

In the somewhat unusual case in which your unit test resides in a different module from that which contains your file support code (DataLoader, DataObject, etc.), you will need to add a <test /> dependency on the module which contains the file support code. Currently this can only be done by editing the project.xml file for the module containing your unit tests. See the build harness' README for more information; you can find the relevant section by searching for test-dependencies in that file.

Older versions than 6.5

If you are writing a test for a DataObject, you need to set up enough of the DataLoader infrastructure that DataObject.find() will locate your DataLoader and call it to create your DataObject subtype.

First, use the setup code described in Testing Things That Use File Objects. Add to the test's setUp() method a call to FileUtil.setMIMEType() to manually assign the file extension to the MIME type of your DataLoader.

FileUtil.setMIMEType("mf", "text/x-manifest");

(setMIMEType() is deprecated with respect to usage from inside a module, but it is fine to use it in a unit test).

(For XML file subtypes, FileUtil.setMIMEType() on *.xml is not likely to work. You can instead register a MIMEResolver in default lookup which does whatever you need.)

Second, you need to make sure your DataLoader is registered in the default Lookup so that DataObject.find() will find it. In 6.0, the New File Type template will set this up automatically by creating the correct file in test/unit/META-INF/services. (Or you can get better control by using org.openide.util.test.MockLookup.)

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo