I am getting an error while testing my rest application but can't understand why.My error output:
ava.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:98) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248) at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) at java.base/java.util.Optional.orElseGet(Optional.java:364) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.
While I try to do this test:
@DataJpaTest
@ActiveProfiles("test")
public class SaveServiceTest {
@Autowired
private MedsRepo medsRepo;
@Test
void testSaveMeds() {
Meds meds = new Meds(50, "test med", "5,00$", "Flu", 500, "test date");
Meds savedMed = medsRepo.save(meds);
assertThat(savedMed).usingRecursiveComparison().ignoringFields("id").isEqualTo("meds");
}
}
My saveMeds() :
@Service
public class SaveService {
@Autowired
private MedsRepo medsRepo;
public String saveMeds(@RequestBody Meds meds) {
medsRepo.save(meds);
return "Saved Successfully";
}
}
My repository:
public interface MedsRepo extends JpaRepository<Meds,Long> {
}
and Meds :
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Meds {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY )
private long id;//no need for long instead of int
@Column
private String name;
@Column
private String price; //ask if not used in operations
@Column
private String category;
@Column
private int pillNumber;
@Column
private String date;
}´´´
The error stops the test in the line:
I do not understand the problem. I call the SaveService in a controller:
``` @RestController
public class Controller {
@Autowired
private MedsRepo medsRepo;
@Autowired
private SaveService saveService;
@Autowired
private UpdateService updateService;
@Autowired
DeleteService deleteService;
@GetMapping("/medicines")
public List<Meds> getMedicine(){
return medsRepo.findAll();
}
@PostMapping(value = "/save")
public String saveMeds(@RequestBody Meds meds){
return saveService.saveMeds(meds);
}
@PutMapping(value = "/update/{id}")
public String updateMeds(@PathVariable long id, @RequestBody Meds meds){
return updateService.updateMeds(id, meds);
}
@DeleteMapping("/delete/{id}")
public String deleteMeds(@PathVariable long id){
return deleteService.deleteMeds(id);
}
}´´´
CodePudding user response:
Duplicate: Spring Boot - Error creating bean with name 'dataSource' defined in class path resource
Spring boot is trying to load an inject dependencies in this spring class when you run your tests:
org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class
Either you provide all necessary configuration for this class in application-test.properties (or application-test.yml, if it's your case) or you disable this class from loading like mentioned in the link above.
CodePudding user response:
You shouldn't to use request body annotation in service, we use it in controller.