【问题标题】:How can be tested service layer while using multiple dependent services in spring boot在spring boot中使用多个依赖服务时如何测试服务层
【发布时间】:2020-01-07 00:44:00
【问题描述】:

我正在 Spring Boot 中编写一些测试。我想编写所有类型的测试。如单元测试、集成测试、组件测试、微服务测试。我该怎么做?

我编写了单元测试,但我无法编写其他测试。当我想编写集成测试时,我遇到了一些问题。依赖注入的问题。我有一个服务类,该服务类包含多个依赖项(其他服务,这些其他服务包含其他服务等等)。如何测试服务层?我需要模拟或使用真正的 bean 吗?

【问题讨论】:

标签: java spring-boot integration-testing


【解决方案1】:

如果您正在执行单元测试,则需要模拟您正在测试的类范围之外的任何依赖项。 对于集成测试,您需要自动装配依赖项并创建您正在测试的服务。 假设您要测试需要存储库类来运行的服务类,您可以这样做 这是您要测试的服务,它依赖于存储库

@Service
public class SomeService {
public final SomeRepository someRepository
public SomeService(SomeRepository someRepository){
  this.someRepository = someRepository;
}
public Object someMethod (){ return someRepository.getSomething()}
}

这就是您在集成中测试它的方式

@SpringBootTest(classes = Application.class)
public class SomeServiceTest(){
  @Autowired
  SomeRepository someRepository;

  SomeService someService;

 @Before
public void setup(){
  someService = new SomeService(someRepository);
}

@Test
public void someMethodTest(){

 Assert.assertTrue(someService.someMethod().equals(anObject))
}
}

【讨论】:

  • 如果SomeService中还有其他服务,我应该创建另一个服务的实例并将其注入SomeService类吗?
  • 如果 SomeService 依赖于 AnotherService 你可以这样做
  • 啊哈明白我会尝试的。谢谢
  • 好的。如果有帮助,我会做
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 2022-01-08
  • 2020-12-09
  • 1970-01-01
  • 2021-03-26
  • 2020-02-10
  • 2019-12-08
  • 1970-01-01
相关资源
最近更新 更多