mercredi 24 février 2016

Set custom Annotation inside method?

I develop simple unit test library, just for fun and experience. As long as I write unit tests, I follow given-when-then or arrange-act-assert pattern. So I thought, that instead of write this pattern names as single line comments in test method body:

@TestClass(enabled = false)
public class DemonstrationTest {

    @UnitTest
    public void StringBuilderSuccess() throws AssertFailureException{
        //Given
        String firstTitle = "CosmicWhale";
        String secondTitle = "AmbientTurtle";
        StringBuilder stringBuilder = new StringBuilder();
        String expected = firstTitle + " " + secondTitle;

        //When
        String actual = stringBuilder.append(firstTitle).append(" ").append(secondTitle).toString();

        //Then
        btester.framework.Assert.assertEquals(expected, actual);
    }
}

I can create annotations, to follow this pattern. This is much more elegant:

@UnitTest
    public void StringBuilderSuccess() throws AssertFailureException{
        @Given
        String firstTitle = "CosmicWhale";
        String secondTitle = "AmbientTurtle";
        StringBuilder stringBuilder = new StringBuilder();
        String expected = firstTitle + " " + secondTitle;

        @When
        String actual = stringBuilder.append(firstTitle).append(" ").append(secondTitle).toString();

        @Then
        String localVariable;
        btester.framework.Assert.assertEquals(expected, actual);
    }

My problem is, that each of these annotations, must be above some local variable. This is not a problem with @Given and @When annotations, but it is a big problem with the last, @Then annotation. I've created redundand local variable under @Then annotation, to bypass the problem.

Question: Is there any chance to place annotation above Assert in the code?

Each annotation body looks lika this:

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.LOCAL_VARIABLE)
public @interface When {

}

I'm using Java 8. I will be grateful for any help.

Ps. If you want to check or contribute my project, you can found it here.

Aucun commentaire:

Enregistrer un commentaire