Overview

Currently, @TestBean factory methods must be defined in the test class, one of its superclasses, or in an implemented interface.

However, users may wish to define common factory methods in external classes that can be shared easily across multiple test classes simply by referencing an external method via a fully-qualified method name.

Example

Given the following test utility...

package example;

public class TestBeanFactory {

    public static String createTestMessage() {
        return "test";
    }

}

... the following should be supported:

@SpringJUnitConfig
class TestBeanForExternalFactoryMethodIntegrationTests {

    @TestBean(methodName = "example.TestBeanFactory#createTestMessage")
    String message;


    @Test
    void test() {
        assertThat(message).isEqualTo("test");
    }


    @Configuration
    static class Config {

        @Bean
        String message() {
            return "prod";
        }
    }

}

Proposal

To align with the syntax used for fully-qualified method names in @MethodSource and fully-qualified field names in @FieldSource in JUnit Jupiter, I propose that we allow test bean factory methods to be referenced via a fully-qualified method name following the syntax <fully-qualified class name>#<method name>.

Related Issues

  • 32943

Comment From: sbrannen

Current work on this issue can be viewed in the following feature branch.

  • https://github.com/spring-projects/spring-framework/compare/main...sbrannen:spring-framework:issues/gh-33125-TestBean-fully-qualified-method-names