vendredi 27 septembre 2019

Spring test: Parameter 0 of constructor in BlogService required a bean of type BlogPostRepository

I have a BlogPostRepository which is an interface JpaRepository:

@Repository
@Primary
public interface BlogPostRepository extends JpaRepository<BlogPost, Long> {
    @Query("SELECT p FROM BlogPost p WHERE slug = ?1")
    List<BlogPost> findBySlug(String slug);
}

When I run the following test, Spring is not able to load the BlogPostRepository, according to this error:

Parameter 0 of constructor in com.example.demo.Services.BlogService required a bean of type 'com.example.demo.Repositories.BlogPostRepository' that could not be found.

My test looks like:

@RunWith(SpringRunner.class)
@WebMvcTest(BlogController.class)
@ContextConfiguration(classes = {DemoApplication.class,BlogController.class})
public class BlogControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception
    {
        MvcResult result = this.mockMvc.perform(get("/blog"))
                //.andDo(print())
                .andExpect(status().isOk())
                .andReturn();
        assertTrue(result.getResponse().getContentAsString().contains("Hello world"));
    }
}

The problem is I cannot define the BlogPostRepository as a bean, since it is an interface:

@Bean
public ExceptionFactory exceptionFactory()
{
    return new BlogPostRepository(); //this does not work! -> cannot construct interface
}

This only occurs during an integration test.

Aucun commentaire:

Enregistrer un commentaire