我已经使用 Java、Selenium、Junit、Maven 开发了一整套自动化测试。
对于每项测试,他们都有一个或多个@Category 注释来描述每个测试涵盖的软件领域。例如:
@Test
@Category({com.example.core.categories.Priority1.class,
com.example.core.categories.Export.class,
com.example.core.categories.MemberData.class})
@Test
@Category({com.example.core.categories.Priority1.class,
com.example.core.categories.Import.class,
com.example.core.categories.MemberData.class})
@Test
@Ignore
@Category({com.example.core.categories.Priority2.class,
com.example.core.categories.Import.class,
com.example.core.categories.MemberData.class})
我想做的是找到一种方法来计算有多少测试包含任何给定的类别。所有可能的类别都是 //com/example/core/categories 文件夹中的文件名作为源列表。
我已经尝试构建一个 shell 脚本来进行字数统计,这似乎工作正常,但我认为会有更多“内置”的东西来处理 @Category。
我最大的问题是,即使我得到了正确的计数,一个或多个测试也很可能被标记为@Ignore,这应该使测试@Category 无效,但没有大量使用标志并读取每个文件行 -按顺序排列,以便抛出正确的计数。
是否有一种很好的方法来逐项列出@Category 的因素,这也是@Ignore 的因素?
示例输出
| Category | Count |
|----------------------------------------------|------:|
| com.example.core.categories.Export.class | 1 |
| com.example.core.categories.Import.class | 1 |
| com.example.core.categories.MemberData.class | 2 |
| com.example.core.categories.Priority1.class | 2 |
| com.example.core.categories.Priority2.class | 0 |
| com.example.core.categories.Priority3.class | 0 |
最佳答案
(推荐方法)
我尝试了一种在抽象层中使用计数器来执行此操作的方法,但这很痛苦,必须在每个测试方法的开头添加源代码。
最后,这是我为满足您的需求而编写的源代码;它相当繁重(反射......),但它对现有源代码的干扰较小,并且完全满足您的需求。
首先,您必须创建一个测试套件(包含各种其他套件,或直接包含您想要的所有测试类),以确保最后,您想要统计的所有测试都已加载.
在这个套件中,你必须实现一个名为
这是我为您编写的测试套件实现: 你可以适应你的需要,特别是我在开始时创建的常量,来过滤要考虑的包。 然后你就没有比你已经做的更多的事了。 例如,这是我的小测试类: 在这种情况下,输出是: 以及包含 你得到输出: 如果需要,您可以轻松删除“(Ignored Tests)”注册,当然也可以根据需要调整输出。 这个最终版本的优点在于,它会处理真正加载/执行的测试类,因此您将拥有已执行内容的真实统计信息,而不是像您这样的静态统计信息到目前为止。 如果您希望像您所要求的那样,不对现有源代码做任何事情,这是一种静态执行类别测试计算的方法。 这是我为您编写的 你只需要修改开头的两个常量来指定: 这个新版本的想法: 如果您需要更多信息,请告诉我。@AfterClass 的“final Hook”,当整个测试套件完全由 JUnit< 管理时,它将被调用一次。/strong="">.package misc.category;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.AfterClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ UnitTestWithCategory.class })
public class TestSuiteCountComputer {
public static final String MAIN_TEST_PACKAGES = "misc.category";
private static final Class<?>[] getClasses(final ClassLoader classLoader)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> CL_class = classLoader.getClass();
while (CL_class != java.lang.ClassLoader.class) {
CL_class = CL_class.getSuperclass();
}
java.lang.reflect.Field ClassLoader_classes_field = CL_class.getDeclaredField("classes");
ClassLoader_classes_field.setAccessible(true);
Vector<?> classVector = (Vector<?>) ClassLoader_classes_field.get(classLoader);
Class<?>[] classes = new Class[classVector.size()]; // Creates an array to avoid concurrent modification
// exception.
return classVector.toArray(classes);
}
// Registers the information.
private static final void registerTest(Map<String, AtomicInteger> testByCategoryMap, String category) {
AtomicInteger count;
if (testByCategoryMap.containsKey(category)) {
count = testByCategoryMap.get(category);
} else {
count = new AtomicInteger(0);
testByCategoryMap.put(category, count);
}
count.incrementAndGet();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
Map<String, AtomicInteger> testByCategoryMap = new HashMap<>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
while (classLoader != null) {
for (Class<?> classToCheck : getClasses(classLoader)) {
String packageName = classToCheck.getPackage() != null ? classToCheck.getPackage().getName() : "";
if (!packageName.startsWith(MAIN_TEST_PACKAGES))
continue;
// For each methods of the class.
for (Method method : classToCheck.getDeclaredMethods()) {
Class<?>[] categoryClassToRegister = null;
boolean ignored = false;
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof org.junit.experimental.categories.Category) {
categoryClassToRegister = ((org.junit.experimental.categories.Category) annotation).value();
} else if (annotation instanceof org.junit.Ignore) {
ignored = true;
} else {
// Ignore this annotation.
continue;
}
}
if (ignored) {
// If you want to compute count of ignored test.
registerTest(testByCategoryMap, "(Ignored Tests)");
} else if (categoryClassToRegister != null) {
for (Class<?> categoryClass : categoryClassToRegister) {
registerTest(testByCategoryMap, categoryClass.getCanonicalName());
}
}
}
}
classLoader = classLoader.getParent();
}
System.out.println("\nFinal Statistics:");
System.out.println("Count of Tests\t\tCategory");
for (Entry<String, AtomicInteger> info : testByCategoryMap.entrySet()) {
System.out.println("\t" + info.getValue() + "\t\t" + info.getKey());
}
}
}
package misc.category;
import org.junit.Test;
import org.junit.experimental.categories.Category;
public class UnitTestWithCategory {
@Category({CategoryA.class, CategoryB.class})
@Test
public final void Test() {
System.out.println("In Test 1");
}
@Category(CategoryA.class)
@Test
public final void Test2() {
System.out.println("In Test 2");
}
}
In Test 1
In Test 2
Final Statistics:
Count of Tests Category
1 misc.category.CategoryB
2 misc.category.CategoryA
@Ignore 注释的测试用例:package misc.category;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
public class UnitTestWithCategory {
@Category({CategoryA.class, CategoryB.class})
@Test
public final void Test() {
System.out.println("In Test 1");
}
@Category(CategoryA.class)
@Test
public final void Test2() {
System.out.println("In Test 2");
}
@Category(CategoryA.class)
@Ignore
@Test
public final void Test3() {
System.out.println("In Test 3");
}
}
In Test 1
In Test 2
Final Statistics:
Count of Tests Category
1 (Ignored Tests)
1 misc.category.CategoryB
2 misc.category.CategoryA
静态“按类别测试”计算机
StaticTestWithCategoryCounter:import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
public class StaticTestWithCategoryCounter {
public static final String ROOT_DIR_TO_SCAN = "bin";
public static final String MAIN_TEST_PACKAGES = "misc.category";
private static final Class<?>[] getClasses(final ClassLoader classLoader)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> CL_class = classLoader.getClass();
while (CL_class != java.lang.ClassLoader.class) {
CL_class = CL_class.getSuperclass();
}
java.lang.reflect.Field ClassLoader_classes_field = CL_class.getDeclaredField("classes");
ClassLoader_classes_field.setAccessible(true);
Vector<?> classVector = (Vector<?>) ClassLoader_classes_field.get(classLoader);
Class<?>[] classes = new Class[classVector.size()]; // Creates an array to avoid concurrent modification
// exception.
return classVector.toArray(classes);
}
// Registers the information.
private static final void registerTest(Map<String, AtomicInteger> testByCategoryMap, String category) {
AtomicInteger count;
if (testByCategoryMap.containsKey(category)) {
count = testByCategoryMap.get(category);
} else {
count = new AtomicInteger(0);
testByCategoryMap.put(category, count);
}
count.incrementAndGet();
}
public static void computeCategoryCounters() throws Exception {
Map<String, AtomicInteger> testByCategoryMap = new HashMap<>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
while (classLoader != null) {
for (Class<?> classToCheck : getClasses(classLoader)) {
String packageName = classToCheck.getPackage() != null ? classToCheck.getPackage().getName() : "";
if (!packageName.startsWith(MAIN_TEST_PACKAGES))
continue;
// For each methods of the class.
for (Method method : classToCheck.getDeclaredMethods()) {
Class<?>[] categoryClassToRegister = null;
boolean ignored = false;
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof org.junit.experimental.categories.Category) {
categoryClassToRegister = ((org.junit.experimental.categories.Category) annotation).value();
} else if (annotation instanceof org.junit.Ignore) {
ignored = true;
} else {
// Ignore this annotation.
continue;
}
}
if (ignored) {
// If you want to compute count of ignored test.
registerTest(testByCategoryMap, "(Ignored Tests)");
} else if (categoryClassToRegister != null) {
for (Class<?> categoryClass : categoryClassToRegister) {
registerTest(testByCategoryMap, categoryClass.getCanonicalName());
}
}
}
}
classLoader = classLoader.getParent();
}
System.out.println("\nFinal Statistics:");
System.out.println("Count of Tests\t\tCategory");
for (Entry<String, AtomicInteger> info : testByCategoryMap.entrySet()) {
System.out.println("\t" + info.getValue() + "\t\t" + info.getKey());
}
}
public static List<String> listNameOfAvailableClasses(String rootDirectory, File directory, String packageName) throws ClassNotFoundException {
List<String> classeNameList = new ArrayList<>();
if (!directory.exists()) {
return classeNameList;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
if (file.getName().contains("."))
continue;
classeNameList.addAll(listNameOfAvailableClasses(rootDirectory, file, packageName));
} else if (file.getName().endsWith(".class")) {
String qualifiedName = file.getPath().substring(rootDirectory.length() + 1);
qualifiedName = qualifiedName.substring(0, qualifiedName.length() - 6).replaceAll(File.separator, ".");
if (packageName ==null || qualifiedName.startsWith(packageName))
classeNameList.add(qualifiedName);
}
}
return classeNameList;
}
public static List<Class<?>> loadAllAvailableClasses(String rootDirectory, String packageName) throws ClassNotFoundException {
List<String> classeNameList = listNameOfAvailableClasses(rootDirectory, new File(rootDirectory), packageName);
List<Class<?>> classes = new ArrayList<>();
for (final String className: classeNameList) {
classes.add(Class.forName(className));
}
return classes;
}
public static void main(String[] args) {
try {
loadAllAvailableClasses(ROOT_DIR_TO_SCAN, MAIN_TEST_PACKAGES);
computeCategoryCounters();
} catch (Exception e) {
e.printStackTrace();
}
}
}
null 以表示 100% 可用包)
关于java - 获取 @Category 在 JUnit 的一组测试中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52863196/
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当
我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r
我在app/helpers/sessions_helper.rb中有一个帮助程序文件,其中包含一个方法my_preference,它返回当前登录用户的首选项。我想在集成测试中访问该方法。例如,这样我就可以在测试中使用getuser_path(my_preference)。在其他帖子中,我读到这可以通过在测试文件中包含requiresessions_helper来实现,但我仍然收到错误NameError:undefinedlocalvariableormethod'my_preference'.我做错了什么?require'test_helper'require'sessions_hel
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url