Reputation: 1
MockMvc calling the controller but unable to creating @Autowired objects in controller class: AuthControllerTest.java
@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
class AuthControllerTest {
private MockMvc mockMvc;
@InjectMocks
private AuthController authController;
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(authController)
.build();
}
@Test
void getToken() throws Exception{
mockMvc.perform(post("/auth/token")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\" : \"Santa Clause\", \"password\" : \"1223\" }")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("Success"))
.andExpect(jsonPath("$.result").exists())
.andExpect(jsonPath("$.result.username").exists())
.andExpect(jsonPath("$.result.token").exists())
.andDo(print());
}
}
AuthController.java
@RestController
@RequestMapping("/auth")
public class AuthController extends ContextService {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
@Autowired
IAuthManagement authManagement;
@PostMapping("/token")
public ResponseEntity getToken(@RequestBody AuthenticationDTO data) throws UserException {
logger.info("\nCreating a new Token for user from credentials passed. *** "+data.getUsername()+"-->"+data.getPassword()+"-->"+authManagement);
return authManagement.getToken(data);
}
Output:
Creating a new Token for user from credentials passed. *** Santa Clause-->1223-->null
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
@InjectMocks is not injecting anything because authManagement is null and hence the nullPointerException. Can anyone please help me to solve the issue.
Upvotes: 0
Views: 1734
Reputation: 5758
You need to mock IAuthManagement authManagement;
In your test class add something like this..
@Mock
IAuthManagement authManagement;
In addition to this you'll have to mock your service method too. https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/
In the above tutorial take a look at the test class, line 50, you'll have to do something like.. when()
so that it won't return null
Upvotes: 1