简体   繁体   中英

How can be tested service layer while using multiple dependent services in spring boot

I am writing some tests in spring boot. I want to write all types of tests. Such as unit test, integration test, component test, microservice test. How can I do it?

I wrote unit tests, But I could not write other tests. When I wanted to write integration tests, I faced some problems. The problems with dependency injection. I have a service class, the service class contains multiple dependencies(Other services, these other services contain other services and so on). How can I test the service layer? Do I need mocking or working with real beans?

if you are doing unit tests you need to mock any dependency that is outside the scope of the class you are testing. For integration tests you need to autowire the dependencies and create the service you are testing. Lets say you want to test a service class that need a repository class to run you can do it this way this is the service you want to test that depends on a repository

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

this is how you test it in integration

@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))
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM