Issue
I'm new to Java development so sorry in advance if I'm not using the appropriate terms.
Whenever I run a test on a class that needs to save something in my database, I face a NullPointerException on the Autowired repository.
I use Junit4, here are code snippets :
application-test.properties
spring.datasource.url=jdbc:tc:mysql:8.0.29://localhost:3306/MYSERVICE
MyService.java
@Component
class MyService {
@Autowired MyRepository myRepository;
public void mainFunction() {
myRepository.saveSomething();
}
}
MyRepository.java
@Repository
public interface MyRepository extends JpaRepository<T, Long> {
void saveSomething();
}
MyServiceTest.java
public class myServiceTest extends TestConfiguration {
@Rule
public MySQLContainer mysql = new MySQLContainer();
@InjectMocks MyService myService;
@Test
public void mainFunctionTest() {
myService.mainFunction()
}
}
MyServiceTestApplication.java
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class
})
public class MyServiceTestApplication{
}
TestConfiguration.java
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceTestApplication.class)
@ActiveProfiles("test")
public abstract class TestConfiguration {
}
When I run the test in debug mode, I can see that myRepository is null
Any help would be highly appreciated
Thanks :)
Edit 01/08/2022 : Add @Component on MyService
Edit 01/08/2022 (2) : Add MyServiceTestApplication.java and TestConfiguration.java
Solution
It seems, you forgot to annotate the class MyService
with @Service
.
With this annotation being made at that class, the Spring framework will recognize it:
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
Given that the rest of the configuration is working, the @Autowired
dependency injection mechanism will hereby provide you with an instance of the @Repository
you requested, at runtime, here your test setup.
Answered By - MWiesner
Answer Checked By - Terry (JavaFixing Volunteer)