InitSpring启动模拟在注入之前

zbsbpyhn  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(283)

在将模拟注入另一个组件之前,是否有方法对其进行初始化?
举个例子,我有以下课程:

@Service
SomeService {
    @Autowired
    public SomeService(SomeConfig config)
}

@Configuration
@Getter
@Setter
public class SomeConfig {
  private String someValue;
}

在我的测试中,我做了以下几点:

@MockBean
SomeConfig someConfig;

@Autowired
SomeService someService;

问题是 SomeService 构造函数已在访问 SomeConfig 各位成员,我还没来得及用 when(someConfig.getSomeValue()).thenReturn("something") ,导致 NullPtrException .
有没有一个钩子在 SomeService 是否示例化?

s2j5cfk0

s2j5cfk01#

您可以在安装方法中手动设置服务。
只需确保在这些测试中从类路径扫描中排除someservice。

SomeServiceTest {
  @MockBean
  SomeConfig someConfig;

  SomeService someService;

  @BeforeEach
  public void setup(){
    // init mocks
    // setup other stuff

    someService = new SomeService(someConfig);
  }

}
6yjfywim

6yjfywim2#

我假设someservice看起来像:

@Service
SomeService {

    private final SomeConfig config

    @Autowired
    public SomeService(SomeConfig config) {
       this.someConfig = someConfig;
       // some logic with config getters
    }
}

您应该在一个单独的方法中使用annotation@postconstruct,并将config getter的用法放在那里,例如:

@PostConstruct
private void postConstruct() {
// some logic with config getters
}

相关问题