lukaszrys
lukaszrys

Reputation: 1786

JUnit : when testing method with annotation, test ignores annotation

I have really weird issue. Heres my method

@SomeAnnotation(value = "test")
public void doSomethink() {
   ..
}

When I'm using my application everythink works fine (when calling method doSomethink() in debug it also goes inside annotation), but when I run test like below

@Test
public void testDoSomethink() {
   service.doSomethink();    
}

My test completly ignores annotation and goes straight into doSomethink method. Am i missing somethink? I think that piece of code is enough but let me know if you need some more.

SomeAnnotation

package org.springframework.security.access.prepost;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SomeAnnotation{
    String value();
}

By ignore i mean that when running through test it simply bypass annotation like its not even there

Upvotes: 0

Views: 698

Answers (2)

cody.tv.weber
cody.tv.weber

Reputation: 646

See this later answer -> https://stackoverflow.com/a/60299629/3661748

Essentially, you have to create a validator. Then use that validator to validate the class.

That validator will trigger the annotations and collect the violations into an iterable collection.

You can extract those violations to validate individual messages if you want some thorough testing.

Upvotes: 0

Alexander Rühl
Alexander Rühl

Reputation: 6939

Annotations are not code which gets executed, but it is meta-information which needs an annotation processor to do something with it.

In case of Java EE for example, the annotations are processed by the container (e.g. the app server you use) and result in doing additional things like setting up a transaction or do a mapping between entity and table.

So in your case, it seems that you expect Spring to do something with the annotation (which you experience when debugging your application). When running the test case, there is no framework or container doing it, so you have to either mock or simulate that, or use something like Arquillian to run your test within the needed environment (e.g. a container).

Upvotes: 1

Related Questions