【发布时间】:2019-10-13 23:31:00
【问题描述】:
我有一个测试实用程序,我需要每个测试方法都有一个新实例(以防止测试之间的状态泄漏)。到目前为止,我使用的范围是“原型”,但现在我希望能够将该实用程序连接到另一个测试实用程序,并且每次测试的连接实例都应相同。
这似乎是一个标准问题,所以我想知道是否有“测试方法”范围或类似的东西?
这是测试类和测试实用程序的结构:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
@Autowired
private TestDriver driver;
@Autowired
private TestStateProvider state;
// ... state
// ... methods
}
@Component
@Scope("prototype") // not right because MyTest and TestStateProvider get separate instances
public class TestDriver {
// ...
}
@Component
public class TestStateProvider {
@Autowired
private TestDriver driver;
// ...
}
我知道我可以使用 @Scope("singleton") 和 @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) 但这比我需要的刷新更多 - 每个测试一个新的 TestDriver 实例就足够了。此外,这种方法容易出错,因为所有使用TestDriver 的测试都需要知道它们还需要@DirtiesContext 注释。所以我正在寻找更好的解决方案。
【问题讨论】:
标签: java spring spring-boot dependency-injection spring-test