Xtests (Junit and NBJunit) in Netbeans 6.0
XTest Infrastructure Setup
The Netbeans Infrastructure should be automatically setup unless you are using
Junit 4.1 on Mileston Releases.
In order to develop Junit 4.1 tests on a Milestone release you will need an additional plugin.
- You can now go to the plugin manager
- Select Available Pluggins
- Do a search for "unit"
- Download the following pluggins:
- NB Junit
- NB Junit IDE Integration
- XTests Module
- You may want to restart Netbeans just in case.
XTest Framework Creation
- Make sure your module is Set As Main".
- Create XTest Infrastructure "File"->"New File".
- Select "Testing Tools" and then "Xtest Infrastructure".
- Notice files and folders generated.
Note: You may have to create a subdirectory test/unit/src
Create NbJunit Test.
- Right click on the class you would like to create a unit test for.
- Select "Tools"->"Create Junit Test"
- Select version 4.1 and continue through until Test is created.
- You can see your new test in the Project Window under node "Unit Test" and package name.
Framework Not Found?
- This area seems to be buggy but there are a couple of things you can do.
- You want to make sure junit.jar is add to your classpath, you can either do this by modifying your command line call in etc/netbeans.conf. Here is one method of do something similar.
- I downloaded junit4.1 and placed the jar file in NETBEANSHOME/netbeans/java1/modules/ext/junit4.1.jar
- Select the Tools menu -> Libraries
- Select "New Library..."
- Name it JUnit4.1
- NETBEANSHOME/netbeans/java1/modules/ext/junit4.1.jar
- specify the sources as junit-4.1-src.jar
- specify javadoc jnit4.1/javadoc
- Also you can add to your project properties the following lines (or add it to your private properties if you are planning on commiting this file).
test.unit.cp.extra=${junit.dir}/modules/ext/junit-4.1.jar
test.junit.jar=/usr/lib/junit4.1/junit-4.1.jar
- You may need to restart Netbeans when ever adding anything to your classpath.
Setup Dependencies
- Update: you can now right click on the "Test Dependencies folder in the Project Window to add test library dependencies just like you would add a dependency to your module. You can also specify wether it is recursive or to grab a dependencies test folder by right-clicking on a library and selecting properties. The below steps are no longer necessary but may still be of interest.
- You can refer to the following link on how to add test dependencies http://wiki.netbeans.org/wiki/view/ModuleDependenciesForTests
- In general you will add
...
</module-dependencies>
<test-dependencies>
<test-type>
<name>unit</name>
<test-dependency>
<code-name-base>org.netbeans.modules.web.project</code-name-base>
<recursive/>
<compile-dependency/>
</test-dependency>
</test-type>
</test-dependencies>
- To insure that all your test dependencies work, right click on your poject in the projects window. Select XTest->Build Unit Tests. In some cases you may see -missing-Module-Entries-: org.netbeans.modules.xxx.... This means that this dependency isnot recognized.
- Be cautious about using the <recursive/>. Although this make sure you have all sub-classes, you may get a dependencies.txt too large error.
- In some cases you want to use a modules test folder. In order to do this you must include <test/>. org.openide.util is a good example of this.
- During runtime, if you run into java.lang.NoClassDefFoundError: ...,
you will need to add that class' module to your run dependencies as well.
(This is usually most easily done by adding recursive test dependencies.)
File System Calls
If you plan to use FileObject you have to
setup the MasterFileSystem.
Initializing the Layers
http://wiki.netbeans.org/wiki/view/LayerInitialization?version=3
Writing Tests For DataObjects and DataLoaders
In order to use DataObject, you will need to setup enough DataLoader infrastructure that DataObject.find() will locate your object.
http://wiki.netbeans.org/wiki/view/DevFaqTestDataObject
USeful Test Classes
Setting up Services
- There are two way to setup services. Either through the META-INF folder in your unit/test directory or through the MockServices.setServices(classes) method.
Setting up a Mock Project
XXX rather than copying and pasting code like this from the wiki,
you should define useful utility methods in an appropriate module and maintain them.
-jglick
- See attached zip file for Mock Project NBJunitTest/TestJSFApp.zip
- Setup MockOpenProjectTrampoline
public static final class MockOpenProjectsTrampoline implements OpenProjectsTrampoline {
private Collection<Project> openProjects = new ArrayList<Project>();
public MockOpenProjectsTrampoline() {
super();
}
public Project[] getOpenProjectsAPI() {
Project projects[] = new Project[ openProjects.size() ];
openProjects.toArray( projects );
return projects;
}
public void openAPI(Project[] projects, boolean openRequiredProjects) {
for( Project project : projects ){
openProjects.add(project);
mainProject = project;
}
}
public void closeAPI(Project[] projects) {
for( Project project : projects ){
openProjects.remove(project);
}
}
public void addPropertyChangeListenerAPI(PropertyChangeListener listener, Object source) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void removePropertyChangeListenerAPI(PropertyChangeListener listener) {
throw new UnsupportedOperationException("Not supported yet.");
}
private Project mainProject;
public Project getMainProject() {
return mainProject;
}
public void setMainProject(Project project) {
if (mainProject != null && !openProjects.contains(mainProject)) {
throw new IllegalArgumentException("Project " + ProjectUtils.getInformation(mainProject).getDisplayName() + " is not open and cannot be set as main.");
}
this.mainProject = mainProject;
}
}
- Define Unzip Method
private static void unZipFile(File archiveFile, FileObject destDir) throws IOException {
FileInputStream fis = new FileInputStream(archiveFile);
try {
ZipInputStream str = new ZipInputStream(fis);
ZipEntry entry;
while ((entry = str.getNextEntry()) != null) {
if (entry.isDirectory()) {
FileUtil.createFolder(destDir, entry.getName());
} else {
FileObject fo = FileUtil.createData(destDir, entry.getName());
FileLock lock = fo.lock();
try {
OutputStream out = fo.getOutputStream(lock);
try {
FileUtil.copy(str, out);
} finally {
out.close();
}
} finally {
lock.releaseLock();
}
}
}
} finally {
fis.close();
}
}
- Setup service
protected void setUp() throws Exception {
super.setUp();
MockServices.setServices(MockOpenProjectsTrampoline.class);
project = openProject();
}
- Define openProject Method
Project project;
public Project openProject() throws IOException{
String zipResource = "TestJSFApp.zip";
String zipPath = PageFlowViewTest.class.getResource(zipResource).getPath();
assertNotNull(zipPath);
File archiveFile = new File(zipPath);
// FileObject destFileObj = TestUtil.makeScratchDir(this);
FileObject destFileObj = FileUtil.toFileObject( getWorkDir());
unZipFile(archiveFile, destFileObj );
assertTrue( destFileObj.isValid());
FileObject testApp = destFileObj.getFileObject("TestJSFApp");
System.out.println("Children of TestJSFApp:" + Arrays.toString(testApp.getChildren()));
// assertTrue( ProjectManager.getDefault().isProject(testApp));
project = ProjectManager.getDefault().findProject(testApp);
assertNotNull(project);
OpenProjects.getDefault().open(new Project[] {project}, false);
return project;
}
- Write a Test. ;: This is just an example
public void testOpenFacesModel() {
assertTrue(project instanceof WebProject);
WebModule webModule = ((WebProject) project).getAPIWebModule();
assertNotNull(webModule);
FileObject[] facesConfigFiles = ConfigurationUtils.getFacesConfigFiles(webModule);
assertTrue( facesConfigFiles.length == 1);
FileObject facesConfigFile = facesConfigFiles[0];
assertNotNull(facesConfigFile);
// JSFConfigEditorViewFactory factory = ((JSFConfigEditorViewFactory) project.getLookup().lookup(JSFConfigEditorViewFactory.class));
// assertNotNull(factory);
DataObject dataObj = null;
try {
dataObj = DataObject.find(facesConfigFile);
} catch ( DataObjectNotFoundException donefe) {
fail("DataObjectNotFoundException while trying to get DataObject for facesConfigfile: " + donefe);
}
assertNotNull(dataObj);
assertTrue( dataObj instanceof JSFConfigDataObject );
JSFConfigEditorContext context = new JSFConfigEditorContextImpl((JSFConfigDataObject)dataObj);
ArrayList<MultiViewDescription> descriptions =
new ArrayList<MultiViewDescription> (JSFConfigEditorViewFactorySupport.createViewDescriptions(context));
assertTrue(descriptions != null && descriptions.size() > 0);
descriptions.add( new JSFConfigMultiviewDescriptor(context));
Pane pane = (CloneableEditorSupport.Pane) MultiViewFactory.createCloneableMultiView(descriptions.toArray(new MultiViewDescription[descriptions.size()]), descriptions.get(0), null);
assertNotNull( pane );
}
Other Problesm
No Test Folders Found
AssertionFailedError: Method "VWPContentModelProviderTest" not found
- If using NB3, you may need to include an assertion of @Test before your test mthod. However in NBJunit4 this is no longer necessary. You maybe seeing this error is because you do not define a default constructor for you test class.
Useful Resources