i wanted to write Test for my Spring mvc REST Controller. I am following official documentation from https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4 and so just updated version to 1.4
and added spring boot as doc suggests.
I have added following dependencies :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
and the parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
My LoginController API which i want to test looks like this :
@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public @ResponseBody ResponseEntity<HashMap<String, Object>> login() {
// some logic to get Customer
return new ResponseEntity<>(customer, HttpStatus.OK);
}
And as per documentation here is my Test :
@RunWith(SpringRunner.class)
@WebMvcTest(LoginController.class)
@SpringBootTest
public class AuthorizationAndAuthenticationTest extends WebSecurityConfigurerAdapter {
@Autowired
private WebApplicationContext webApplicationContext;
private LoginController loginController;
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private LoggingService loggingService;
@Test
public void test() {
given(this.loggingService.logInfoMessage("some Dummy Message", this.getClass())).
this.restTemplate.getForObject("/login", Object.class);
}
}
Problems : 1. Since login Controller is using many Services, i wanted to Mock them using "given" but it gives compilation problem, seems like i am missing some dependency though not sure. 2.TestRestTemplate is deprecated and what is the alternative ? i did not find any alternative.
This is first time i will be writing Tests using Spring framework so it is possible i am overlooking some minute details.
Please help me with this.
Concerning problem #1: You are probably forgot to call .withReturn
while trying to stub logInfoMessage
:
given(this.loggingService.logInfoMessage("some Dummy Message", this.getClass()))
.willReturn("your desired value")
Concerning problem #2: org.springframework.boot.test.TestRestTemplate is deprecated in favor of org.springframework.boot.test.web.client.TestRestTemplate.
So just change the package.
BTW, most suitable construct for testing Spring MVC endpoints is MockMvc not TestRestTemplate.