单元测试注释?
我问自己,我应该深入(单元)测试我的类。例如,我有以下简单类。
import javax.annotation.security.PermitAll;
import javax.ejb.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path(value = "ping")
@Singleton
@PermitAll
public class PingRestService {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String pingMethod(){
return "pong";
}
}
我写了以下单元测试:
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import javax.annotation.security.PermitAll;
import javax.ejb.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.junit.Test;
public class PingRestServiceTest {
PingRestService prs = new PingRestService();
@Test
public void testClassAnnotations(){
assertEquals(3, prs.getClass().getAnnotations().length);
assertTrue(prs.getClass().isAnnotationPresent(PermitAll.class));
assertTrue(prs.getClass().isAnnotationPresent(Singleton.class));
assertTrue(prs.getClass().isAnnotationPresent(Path.class));
assertEquals("ping", prs.getClass().getAnnotation(Path.class).value());
}
@Test
public void testPingMethodAnnotations() throws SecurityException, NoSuchMethodException{
Method method = prs.getClass().getDeclaredMethod("pingMethod");
assertEquals(2, method.getAnnotations().length);
assertTrue(method.isAnnotationPresent(GET.class));
assertTrue(method.isAnnotationPresent(Produces.class));
assertEquals(1, method.getAnnotation(Produces.class).value().length);
assertEquals(MediaType.TEXT_PLAIN, method.getAnnotation(Produces.class).value()[0]);
}
@Test
public void testPingMethod() {
assertEquals("pong", prs.pingMethod());
}
}
这有意义吗?或者我应该只测试返回的字符串(“pong”,testPingMethod),跳过所有注释测试(testClassAnnotations,testPingMethodAnnotations)?
我认为一些注释是业务逻辑的一部分(例如 PermitAll),因此应该进行测试。