有没有办法编写一个检查Maven依赖项的测试?
在我们的项目中,我们发现了这些问题:
项目的某些部分使用commons-io:commons-io
,其他部分使用org.apache.commons:commons-io
使用了错误版本的依赖项
stax
使用版本1.0-2
和1.0.1
。使用自动依赖性解析,1.0-2
获胜。
所以我想要的是编写一个测试用例,它将当前的依赖树作为输入并对其进行几次检查。这可能吗?
答案 0 :(得分:1)
@Test
public void testCommonsIo() throws Exception {
assertDependencyVersion("commons-io", "commons-io", "2.0");
}
private void assertDependencyVersion(final String groupId,
final String artifactId, final String expectedVersion)
throws IOException {
final StringBuilder sb = new StringBuilder("/META-INF/maven/");
sb.append(groupId).append("/").append(artifactId);
sb.append("/pom.properties");
final String resourcePath = sb.toString();
final InputStream propertiesStream = this.getClass()
.getResourceAsStream(resourcePath);
assertNotNull("no dependency found: " + groupId + ":" + artifactId,
propertiesStream);
final Properties properties = new Properties();
properties.load(propertiesStream);
assertEquals("group", groupId, properties.getProperty("groupId"));
assertEquals("artifact", artifactId, properties.getProperty("artifactId"));
assertEquals("version", expectedVersion, properties.getProperty("version"));
}
同时检查this answer。
这是StAX和其他依赖项的断言方法,它不包含pom.properties
manifest.mf
。如果有很多Properties
次呼叫,可能值得缓存assertDependencyByMetaInf
个实例。
@Test
public void testStaxDependency() throws Exception {
assertDependencyByMetaInf("StAX", "1.0.1");
}
private void assertDependencyByMetaInf(final String specTitle,
final String expectedSpecVersion) throws IOException {
final ClassLoader cl = this.getClass().getClassLoader();
final String resourcePath = "META-INF/MANIFEST.MF";
final Enumeration<URL> resources = cl.getResources(resourcePath);
boolean found = false;
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
final InputStream metaInfStream = url.openStream();
final Properties metaInf = new Properties();
metaInf.load(metaInfStream);
final String metaInfSpecTitle =
metaInf.getProperty("Specification-Title");
if (!specTitle.equals(metaInfSpecTitle)) {
continue;
}
final String specVersion =
metaInf.getProperty("Specification-Version");
assertEquals("version mismatch for " + specTitle,
expectedSpecVersion, specVersion);
found = true;
}
assertTrue("missing dependency: " + specTitle, found);
}
答案 1 :(得分:0)
根据palacsint的建议,这是另一种方法:计算类在类路径上的频率,如果有多个,则打印URL。
private void assertOnceOnClassPath( String resourcePath ) throws IOException {
ClassLoader cl = getClass().getClassLoader();
Enumeration<URL> resources = cl.getResources( resourcePath );
List<URL> urls = new ArrayList<URL>();
while( resources.hasMoreElements() ) {
URL url = resources.nextElement();
urls.add( url );
}
if( urls.size() != 1 ) {
fail( "Expected exactly 1 item:\n" + StringUtils.join( urls, "\n" ) );
}
}