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})
添加回答
举报