I am trying to run a unit test for my springboot controller as:
@WebMvcTest(controllers = MyController.class)
@ExtendWith(SpringExtension.class)
public class MyControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private ValidateRequest validateRequest;
@MockBean
private MyService myService;
@Test
public void createitem_InvalidRequest() throws Exception {
given(validateRequest.validate(any())).willThrow(new InvalidRequestException("Invalid request"));
mvc.perform()
....
....
}
MyController has dependencies ValidateRequest, MyService which are injected at field level using @Autowired.
ValidateRequest is defined as:
@Component
public class ValidateRequest extends SomeBaseClass{
....
....
}
With this setup, I see that validateRequest is not initialized in test, and is null, thus causing NPE.
Java version is 1.8 and sprinbgoot is 2.3.3.
What am I missing here?
Edited:
junit dependencies are:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
6