-2

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?

  • https://stackoverflow.com/questions/57013137/how-to-test-restclient-using-resttemplate-and-junit/57014202#57014202 https://stackoverflow.com/questions/57662014/how-to-write-junit-test-cases-for-rest-controller-service-and-dao-layer-using-s/57664149#57664149 – eHayik Sep 04 '19 at 07:36

1 Answers1

0

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))
}
}
MC Ninjava
  • 214
  • 2
  • 7