22 August, 2006

Working with the Workspace in Eclipse Plug-in Tests

Okay, I've had to figure out how to do this a number of different times that exceeds two; so now I'm writing it down.

The Situation

I want to create a file in the test runtime workspace that I can run tests against.

The Solution, v0.1 ... (beta)

@Before
protected void setUp() throws Exception {
   IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

   // Create a project in the runtime workspace
   IProject project = root.getProject( "My-Test-Project" );
   project.create( null );
   project.open( null );

   // Get a file from the test plug-in's bundle path
   URL url = MyTestPlugin.getDefault().getBundle().getEntry( "/" );
   URL fileUrl = new URL( url, "resources/my-source-file.txt" );
   String filePath = FileLocator.toFileURL( fileUrl ).getFile();
   File sourceFile = new File( filePath );

   // Create a folder and file in the test workspace
   IFolder folder = project.getFolder( "src" );
   folder.create( false, true, null );
   IFile file = folder.getFile( "testfile.txt" );

   // and set its contents to the file from the plug-in
   file.create( new FileInputStream( sourceFile ), false, null );
}

You will have to delete the project in tearDown. Otherwise, the next time setUp gets called, you'll get a ResourceException.

No comments: