spring 我想在注册子bean时阻止父bean的注册

gojuced7  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(95)

UserService.java

@Service
class UserService {
    //target test method
    public int getUser(){
        DbUtil.getMapper(UserMapper.java);
    }
}

字符串
DbUtil.java

class DbUtil {
    
    static DbService dbService;
    
    public static <T> T getMapper(Class<T> clazz){
        if(dbService == null){
            dbService = ((DbService)) ApplicationContextManager.getBean("dbService");
        }
        return dbService.getSqlSessionTemplate().getMapper(clazz);
    }
}


DbService.java

@Autowired
    private SomeConfiguration configuration;
    
    @Autowired
    private SecondConfiguration secondConfiguration;
    
    public SqlSessionTemplate getSqlSessionTemplate(){
        //complecated logic...
    }


FakeDbService.java

@Service
class FakeDbService extends DbService {
    public SqlSessionTemplate getSqlSessionTemplate(){
        // simple logic ...
    }
}


测试配置

@Configuration
@Import(FakeDbService.class)
class TestConfiguration {
    
}


Test.java

@ContextConfiguration(classes = TestConfiguration.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
    
    @Autowired
    private UserService userService;
    
    @Test
    public void userServiceTest(){
        userService.getUser();
    }
}


我的目的是测试UserService中的getUser方法。DbUtil类使用ApplicationContextManager.getBean("dbService")导入DbService bean。因为DbService类有很多依赖项,需要额外的依赖项,我试图创建一个FakeDbService,它只覆盖必要的方法并继承DbService。但它不起作用。
在创建spring容器时,不仅注册了FakeDbService bean,还注册了父类DbService bean。由于spring容器在执行时没有添加对DbService的依赖,因此出现了找不到bean的错误。我想在spring容器生成过程中防止生成父类DbService
难道不能这样测试吗?或者有其他方法可以在上面的结构中测试?(但是,我不能修改DbServiceDbUtil的源代码)
感谢你的帮助.

r8xiu3jd

r8xiu3jd1#

创建一个Spring组件,将DbUtil转换为非静态组件:

@Component
class DbUtilComponent {
    public <T> T getMapper(Class<T> clazz) { return DbUtil.getMapper(clazz); }
    ...
}

字符串
将其注入UserService

@Service
class UserService {
    private final DbUtilComponent dbUtilComponent;

    public UserService(DbUtilComponent dbUtilComponent) {
        this.dbUtilComponent = dbUtilComponent;
    }
    //target test method
    public int getUser(){
        dbUtilComponent.getMapper(UserMapper.java);
    }
}


然后使用Mockito进行测试,甚至不要启动Spring上下文。

@ExtendWith(MockitoExtension.class)
public class Test {
    @Mock
    private DbUtilComponent dbUtilComponent;
    @InjectMocks
    private UserService userService;
    
    @Test
    public void userServiceTest(){
        when(dbUtilComponent.getMapper(UserMapper.class)).thenReturn(...);
        userService.getUser();
    }
}

相关问题