-1

I have a test class

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class ApplicationIntegrationTest {


@Autowired
MockMvc mvc;


@Autowired
MyRepository myRepository;

@Test
public void givenCourses() throws Exception{
    MyEntity entity = new Entity();
    myRepository.save(entity);

    mvc.perform(get("/someOperation")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content()
                    .contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}}

MyRepository:

@Repository
 public interface MyRepository extends JpaRepository<MyEntity, Long>, JpaSpecificationExecutor<MyEntity> {}

MyEntity

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder

public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
}

application.properties

spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=false;MODE=MYSQL
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=test
spring.datasource.password=test@123
hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.generate-ddl=true
hibernate.hbm2ddl.auto=create

spring.flyway.validateMigrationNaming= true
spring.flyway.locations= classpath:db/migration/h2

server.port=8082

When running test the Autowired myRepository is getting null. I have tried @RunWith(SpringRunner.class) annotation but getting exception Cannot autowire myRepository No qualifying bean of type MyRepository found

javaDeveloper
  • 1,403
  • 3
  • 28
  • 42

2 Answers2

0

The @Test annotation should be imported from org.junit.jupiter.api.Test

If we use org.junit.Test, the test will use Junit 4 intead of Junit 5

javaDeveloper
  • 1,403
  • 3
  • 28
  • 42
-1

With your current test configuration, you limit the Spring auto configuration of your test application context to two classes: Application and CorsConfig.

By this means, no other auto configuration like the Spring DataSourceAutoConfiguration is triggered, therefore no repository beans are ever going to be instantiated.

Just remove the classes property from the @SpringBootTest annotation, then it will work:

@SpringBootTest
@ActiveProfiles("test")
public class ApplicationIntegrationTest {

Without the classes property, Spring will create the whole application context for your test.

times29
  • 2,782
  • 2
  • 21
  • 40