Now we want to check what we get from AST parser.

For this cause we need more consumers with deeper expectations.

As I will test only single behavior, it is better to put it in an setup method of the test class

        private ASTNode ast;
        ...
        @Before
	public void createAst() {
		String javaCode = "class A {}";
		ASTParser newParser = ASTParser.newParser(AST.JLS3);
		newParser.setSource(javaCode.toCharArray());
		ast = newParser.createAST(new NullProgressMonitor());
	}

The element that we get from AST parser is a compilation unit.
Compilation unit is a smallest chunk of code than can be compiled to binary.
In Eclipse AST class type hierarchy CompilationUnit is a subtype of ASTNode.

        @Test
	public void ensureThatParsedElementIsAnCompilationUnit() throws Exception {
		assertThat(ast, is(CompilationUnit.class));
	}

This looks like a simple and readable Expectation.
It also shows us that “is” Method can be used with a Class instance.

I already explained that “assertThat” uses Matchers to validate assumptions. But how does it work. The Hamcrest Tutorial is a very good place to lookup everything you need.

Any way I would like to introduce another test. It will expect the compilation unit to provide types and one of this types should be our A class.
So hear is the test:

        @Test
	public void ensureThatCompilationUnitHasTypeCalledA() throws Exception {
		CompilationUnit cu = (CompilationUnit)ast;
		List<AbstractTypeDeclaration> allTypes = cu.types();
		assertThat(allTypes, is(notNullValue()));
		assertThat(allTypes, hasItem(isTypeWithName("A")));
	}

And this test is also pretty self explaining and readable.
Here you can see the real power of Matcher. Matcher can be combined with each other and you can also provide your own matcher as I did with “isTypeName”.
So you don’t have to write code for iterating through collection, just nest two Factory Methods will do the trick.

Here is the code of the Matcher I wrote to evaluate a type declaration.

public class TypeHasName extends BaseMatcher<AbstractTypeDeclaration>{
 
	private final String name;
 
	public TypeHasName(String name) {
		this.name = name;
	}
 
	@Override
	public boolean matches(Object item) {
		AbstractTypeDeclaration type = (AbstractTypeDeclaration)item;
		return type.getName().getIdentifier().equals(name);
	}
 
	@Override
	public void describeTo(Description description) {
		description.appendText("type with name ").appendValue(name);
	}
 
	@Factory
	public static TypeHasName isTypeWithName(String typeName) {
		return new TypeHasName(typeName);
	}
}

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Before you submit form:
Human test by Not Captcha

© 2011 Max Blog Suffusion theme by Sayontan Sinha