我正在 IJ 中开发 Java 代码库,目前正在使用 Maven 进行构建。我想用某种形式的契约(Contract)来补充一些代码,这些契约(Contract)将在 Maven 构建中获得。到目前为止,我在寻找这种现成的功能方面一直没有成功:
注:我只关心这里的编译时可检查契约(Contract)。我有 JUnit 可以用于运行时方面。
执行契约(Contract):
我添加了这个部分来回答关于我想要执行什么样的契约(Contract)的评论。理想情况下,我想要最强大的解决方案,条件是该解决方案是完整的。当我在这里说完成时,我的意思是一种契约(Contract)语言和一个契约(Contract)检查器,这样语言中的每个语句都可以在编译时被检查器检查为好/坏。我知道这可能是一个很大的问题,但即使是最简单的契约(Contract),例如those offered by Jetbrains .
对于一个具体的例子,考虑这个函数:
public static Long safeToLong(String value) {
if (value == null) {
return null;
}
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
return null;
}
}
这成功通过了 Jetbrains 合约:
@Contract("null -> null")
并未能通过这个人为的契约(Contract):
@Contract("null -> !null")
但是有了上面的,人为的,糟糕的契约(Contract),Maven 构建仍然可以正常工作。构建不会获取检查结果 - 这些仅在 IJ 中可见。如果违反任何契约(Contract),我希望能够连接到构建并失败。
最佳答案
这是一个适用于 IntelliJ 契约(Contract)的解决方案。这有点乱,但它有效:
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.6.1</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
<configuration>
<properties>
</properties>
<scripts>
<script>file:///${project.basedir}/idea-cli-inspector/ideainspectMvn.groovy</script>
</scripts>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<!-- any version of Groovy \>= 1.5.0 should work here -->
<version>2.5.0</version>
<type>pom</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</plugin>
故障排除
如果您收到 this EXCEPTION_ACCESS_VIOLATION bug在运行检查时,您可以通过在安装 IJ 的文件 bin\idea64.exe.vmoptions 的末尾添加 -Dswing.noxp=true 来修复它 - 修复记录在此 IJ crash thread 的末尾.
Gradle 变体
要将其添加到您的 Gradle 构建中,它比在 Maven 情况下更简单。只需将此任务添加到您的 build.gradle 文件中:
task inspect(type:Exec) {
workingDir '/idea-cli-inspector'
//on windows:
commandLine 'cmd', '/c', 'groovy ideainspect.groovy'
}
关于java - Maven 构建中的契约(Contract)检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50587933/