Issue
I'm trying to use mockmvc but it always shows the error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
My class:
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
@TestPropertySource(locations = "classpath:application-cliente.properties")
public class ClienteRepositoryTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ClienteService clienteService;
@Test
public void simpleMockTest() throws Exception {
var clienteMock = new Cliente("Jessica Pereira");
Mockito.doReturn(Optional.of(clienteMock)).when(clienteService).buscar(2L);
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/clientes/pf/{id}", 1L))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
And my gradle
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.rjdesenvolvimento'
version = '0.0.1'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/milestone' }
}
ext {
set('springCloudVersion', 'Greenwich.SR1')
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-oauth2'
implementation 'org.springframework.cloud:spring-cloud-starter-security'
compileOnly 'org.projectlombok:lombok'
compile('org.glassfish.jaxb:jaxb-runtime:2.3.1')
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'junit', module: 'junit'
} '
testRuntime 'org.junit.jupiter:junit-jupiter-api'
testRuntime 'org.junit.jupiter:junit-jupiter-engine'
testRuntime 'com.h2database:h2'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test {
useJUnitPlatform()
}
Solution
@AutoConfigureMockMvc should be used with @SpringBootTest
or instead you can use @WebMvcTest
to just load Spring MVC infrastructure for limited controller(s).
Often, @WebMvcTest is limited to a single controller and is used in combination with @MockBean to provide mock implementations for required collaborators.
@WebMvcTest also auto-configures MockMvc. Mock MVC offers a powerful way to quickly test MVC controllers without needing to start a full HTTP server.
You can also auto-configure MockMvc in a non-@WebMvcTest (such as @SpringBootTest) by annotating it with @AutoConfigureMockMvc.
Answered By - Amith Kumar
Answer Checked By - Timothy Miller (JavaFixing Admin)