My project is using spring-boot
, sping-data-jpa
, spring-data-rest
, hibernate
I have updated to spring boot 2.3.1
I have solved my problem, so sharing the answer.
We don't need @SpringBootTest
and @ActiveProfiles("unit-test")
on the test class now.
It is working as expected and not calling the actual environmental configuration to run the test. Tests are also super fast as previously.
mport org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.context.SpringBootTest;
@ExtendWith(MockitoExtension.class)
public class MyServiceTest {
@Mock
private MyRepository myRepository;
@InjectMocks
private MyServiceTest myServiceTest;
@BeforeEach
public void setup() {
MyData myData = new MyData();
myData.setName("testName");
myData.setNumber()
Mockito.when(myRepository.findMyDataByNameAndNumber(
Mockito.eq("testName"), Mockito.eq("10101010")).thenReturn(Optional.ofNullable(myData));
}
@Test
void getMyData(){
myServiceTest.getDataByNameAndNumber("testName", "10101010")
Mockito.verify(myRepository, times(1))
.findMyDataByNameAndNumber(Mockito.eq("testName"), Mockito.eq("10101010"));
}
}
Thank you @marc for your suggestion in the comment :)
Could you you please check if you don't enable any profile in your application.yaml if present in your test resource folder like below :-
spring:
profiles:
active: local
Also can you share the snapshot of your project folder.
Firstly looking at your code you are injecting the mocks in to the test class rather than the actual service. Is this how your actual test looks or have you just copied this in so as to not share your actual code?
@InjectMocks
private MyServiceTest myServiceTest;
Secondly this is a unit test so remove the @SpringBootTest annotation. It is adding unnecessary overhead and is probably causing the error through lack of configuration for code you are not actually testing having mocked the repository anyway.