2 回答

TA貢獻1811條經驗 獲得超5個贊
testMethod實現作用域實際上很容易:
public class TestMethodScope implements Scope {
public static final String NAME = "testMethod";
private Map<String, Object> scopedObjects = new HashMap<>();
private Map<String, Runnable> destructionCallbacks = new HashMap<>();
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
if (!scopedObjects.containsKey(name)) {
scopedObjects.put(name, objectFactory.getObject());
}
return scopedObjects.get(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
destructionCallbacks.put(name, callback);
}
@Override
public Object remove(String name) {
throw new UnsupportedOperationException();
}
@Override
public String getConversationId() {
return null;
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
public static class TestExecutionListener implements org.springframework.test.context.TestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) testContext
.getApplicationContext();
TestMethodScope scope = (TestMethodScope) applicationContext.getBeanFactory().getRegisteredScope(NAME);
scope.destructionCallbacks.values().forEach(callback -> callback.run());
scope.destructionCallbacks.clear();
scope.scopedObjects.clear();
}
}
@Component
public static class ScopeRegistration implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
factory.registerScope(NAME, new TestMethodScope());
}
}
}
@Scope("testMethod")只需注冊測試執行偵聽器,所有注釋類型的每個測試都會有一個實例:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners(listeners = TestMethodScope.TestExecutionListener.class,
mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class MyTest {
@Autowired
// ... types annotated with @Scope("testMethod")
}

TA貢獻1853條經驗 獲得超18個贊
我前段時間遇到了同樣的問題并得出了這個解決方案:
使用模擬
我編寫了一些方法來創建特定的 mockito 設置以向每個 mock 添加行為。
因此,使用以下方法和 bean 定義創建一個 TestConfiguration 類。
private MockSettings createResetAfterMockSettings() {
return MockReset.withSettings(MockReset.AFTER);
}
private <T> T mockClass(Class<T> classToMock) {
return mock(classToMock, createResetAfterMockSettings());
}
您的 bean 定義將如下所示:
@Bean
public TestDriver testDriver() {
return mockClass(TestDriver .class);
}
MockReset.AFTER用于在運行測試方法后重置模擬。
最后添加一個TestExecutionListeners到你的測試類:
@TestExecutionListeners({ResetMocksTestExecutionListener.class})
添加回答
舉報