我问自己应该对我的课程进行多深的(单元)测试。
例如,我有以下简单的类。
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),因此应该进行测试。
大多数时候,我们测试的是代码的功能,而不是它的实现方式。这就是所谓的Black Box Testing
(see: http://en.wikipedia.org/wiki/Black-box_testing http://en.wikipedia.org/wiki/Black-box_testing)。
实施测试时,您应该问自己:“要测试的单元可能的输入值是什么?预期结果是什么?”
现在,在测试中,您使用输入值调用代码,并使用预期的结果检查结果,以确保您的代码按照您想要的方式运行。
随着时间的推移,您可能会优化代码而不想要更改功能。那么你不需要改变你的测试。但您可以重新运行它以确保它的行为仍然相同。即使实施方式不同。或者,您可能会更改实现细节,这会对您测试的功能产生副作用。同样在这种情况下,您不需要更改测试,但只需要重新运行它。
在您的简单情况下,您没有输入和一个静态输出,因此您只需调用该方法并检查是否返回“pong”。但现实生活中经过测试的案例很少如此简单。
编辑:您可以看到安全性@PermitAll
配置以及“@Path”配置为输入的 URL 路径,并按照“Boris the Spider”和“Avi”建议的方式在集成测试中测试它们。但其他注释是特定于实现的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)