Skip to content

Allow @TestBean on non-static methods #36980

Description

@hfhbd

Enhancements request

The current syntax to inject a bean in a test is somehow confusing: it requires a field annotated with @TestBean and also a static method. When you use Kotlin, you also need a companion object and @JvmStatic

Ideally, you only need a non static method annotated with @TestBean. This is also symmetric to a regular bean definition.

@SpringBootTest
class CurrentServiceTest {
  @TestBean lateinit var myBean: MyBean

  @Test
  fun testMyService(@Autowired myService: MyService) {}

  companion object {
    @JvmStatic
    fun myBean(): MyBean = MyTestBean()
  }
}

@SpringBootTest
class SimplifiedServiceTest {
  @Test
  fun testMyService(@Autowired myService: MyService) {}

  @TestBean
  fun myBean(): MyBean = MyTestBean() 
}

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: declinedA suggestion or change that we don't feel we should currently apply

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions