Allow TestCompiler SourceFile to work with records
Update `SourceFile` to try a regex replace to make `record` files look like regular classes. Closes gh-29236
This commit is contained in:
parent
8c24e8c034
commit
7fd8e081bb
|
|
@ -41,7 +41,7 @@ dependencies {
|
|||
api("com.sun.xml.bind:jaxb-core:3.0.2")
|
||||
api("com.sun.xml.bind:jaxb-impl:3.0.2")
|
||||
api("com.sun.xml.bind:jaxb-xjc:3.0.2")
|
||||
api("com.thoughtworks.qdox:qdox:2.0.1")
|
||||
api("com.thoughtworks.qdox:qdox:2.0.2")
|
||||
api("com.thoughtworks.xstream:xstream:1.4.19")
|
||||
api("commons-io:commons-io:2.11.0")
|
||||
api("de.bechte.junit:junit-hierarchicalcontextrunner:4.12.1")
|
||||
|
|
|
|||
|
|
@ -171,6 +171,11 @@ public final class SourceFile extends DynamicFile implements AssertProvider<Sour
|
|||
JavaProjectBuilder builder = new JavaProjectBuilder();
|
||||
try {
|
||||
JavaSource javaSource = builder.addSource(new StringReader(content));
|
||||
if (javaSource.getClasses().isEmpty()) {
|
||||
// QDOX doesn't let us inspect records yet, but we only need the
|
||||
// class name so lets make the content look like a class
|
||||
javaSource = builder.addSource(new StringReader(makeRecordsLookLikeClasses(content)));
|
||||
}
|
||||
Assert.state(javaSource.getClasses().size() == 1, "Source must define a single class");
|
||||
JavaClass javaClass = javaSource.getClasses().get(0);
|
||||
return (javaSource.getPackage() != null)
|
||||
|
|
@ -183,6 +188,10 @@ public final class SourceFile extends DynamicFile implements AssertProvider<Sour
|
|||
}
|
||||
}
|
||||
|
||||
private static String makeRecordsLookLikeClasses(String content) {
|
||||
return content.replaceAll("record\\s(\\S+)\\(\\X+?\\)", "class $1");
|
||||
}
|
||||
|
||||
/**
|
||||
* AssertJ {@code assertThat} support.
|
||||
* @deprecated use {@code assertThat(sourceFile)} rather than calling this
|
||||
|
|
|
|||
|
|
@ -119,6 +119,33 @@ class SourceFileTests {
|
|||
assertThat(sourceFile.getContent()).isEqualTo(HELLO_WORLD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClassNameFromSimpleRecord() {
|
||||
SourceFile sourceFile = SourceFile.of("""
|
||||
package com.example.helloworld;
|
||||
|
||||
record HelloWorld(String name) {
|
||||
}
|
||||
""");
|
||||
assertThat(sourceFile.getClassName()).isEqualTo("com.example.helloworld.HelloWorld");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClassNameFromMoreComplexRecord() {
|
||||
SourceFile sourceFile = SourceFile.of("""
|
||||
package com.example.helloworld;
|
||||
|
||||
public record HelloWorld(String name) {
|
||||
|
||||
String getFoo() {
|
||||
return name();
|
||||
}
|
||||
|
||||
}
|
||||
""");
|
||||
assertThat(sourceFile.getClassName()).isEqualTo("com.example.helloworld.HelloWorld");
|
||||
}
|
||||
|
||||
/**
|
||||
* JavaPoet style API with a {@code writeTo} method.
|
||||
*/
|
||||
|
|
|
|||
Loading…
Reference in New Issue