Thomas Escolan
Thomas Escolan

Reputation: 1529

Have legit Spring beans injected into a mock bean

Anyone knows how can I have normal spring beans injected into my MVC controller?

@WebMvcTest(TaskController.class) class TasksManagerApplicationTests {
@Spy // WRONG
private TasksRepository taskDao;
@MockBean
private AssignmentService service;
@MockBean
private ToDoClient client;
@Autowired
private MockMvc template;
...

NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.tskmngt.dao.TasksRepository'

I don't want to mock every dependencies here, it seems to be to much work, only external coupling ones. NB: TasksRepository is Spring Data JPA JpaRepository ; already tried adding @DataJpaTest and failed (Configuration error: found multiple declarations of @BootstrapWith).

Thanks for any help

Upvotes: 0

Views: 232

Answers (1)

Thomas Escolan
Thomas Escolan

Reputation: 1529

Thanks to Joao Dias' remark, here is a (heavier indeed but) executable code:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Slf4j class TasksManagerApplicationTests {
@Mock
private TaskController controller;

@MockBean
private AssignmentService service;
@MockBean
private ToDoClient client;
@Autowired
private MockMvc template;

@LocalServerPort
private int serverport;         // random web server port
@Autowired
private ObjectMapper mapper;    // Jackson serializer

Upvotes: 1

Related Questions