221 lines
No EOL
7.7 KiB
Markdown
221 lines
No EOL
7.7 KiB
Markdown
Coding 5 (Sprint Boot Testing)
|
|
https://www.youtube.com/watch?v=kbr5RaRDgQk&list=PLS1QulWo1RIZ5Vy1lyTlfjqtbut9BijN9
|
|
|
|
- We need mockito and junit runner to test our api and repository so add following in `pom.xml`
|
|
```xml
|
|
<!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform-runner -->
|
|
<dependency>
|
|
<groupId>org.junit.platform</groupId>
|
|
<artifactId>junit-platform-runner</artifactId>
|
|
<version>1.11.0-M2</version>
|
|
<scope>test</scope>
|
|
</dependency>
|
|
|
|
|
|
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
|
|
<dependency>
|
|
<groupId>org.mockito</groupId>
|
|
<artifactId>mockito-core</artifactId>
|
|
<version>5.12.0</version>
|
|
<scope>test</scope>
|
|
</dependency>
|
|
|
|
```
|
|
|
|
- In the following code, some things to be mentioned
|
|
- Mock annotation will mark field as mock and InjectMock will mark a field where injection has to be performed
|
|
- Separate List of records ie objects of Alien class has been created which will be used as repo which is to be expcted later
|
|
- `Before` annotation methods are being used to setup objects or initializing things before testing
|
|
- when method of mockito will expect a result in this case list of records when findAll method is used of repo
|
|
- mockmvc instance is used to mimic controller and its perform method will mimic requests like GET in this case and later it is checking json after checking length of list of records and checking a random ie third record name here
|
|
|
|
in `src/test/java/AlienController.java`
|
|
```java
|
|
package com.example.demo.controller;
|
|
|
|
import java.util.List;
|
|
import java.util.ArrayList;
|
|
import java.util.Arrays;
|
|
|
|
|
|
import static org.hamcrest.Matchers.hasSize; // Import for hasSize
|
|
import static org.hamcrest.Matchers.is;
|
|
import static org.hamcrest.Matchers.notNullValue;
|
|
|
|
// import org.assertj.core.internal.Arrays;
|
|
import org.junit.Before;
|
|
import org.junit.Test;
|
|
import org.junit.runner.RunWith;
|
|
import org.mockito.InjectMocks;
|
|
import org.mockito.Mock;
|
|
import org.mockito.Mockito;
|
|
import org.mockito.MockitoAnnotations;
|
|
import org.mockito.junit.MockitoJUnitRunner;
|
|
import org.springframework.http.MediaType;
|
|
import org.springframework.test.web.servlet.MockMvc;
|
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
|
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|
|
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
|
|
import com.example.demo.model.Alien;
|
|
import com.example.demo.model.TableLoader;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.databind.ObjectWriter;
|
|
|
|
@RunWith(MockitoJUnitRunner.class)
|
|
public class AlienControllerTest {
|
|
private MockMvc mockMvc;
|
|
|
|
ObjectMapper objMapper = new ObjectMapper();
|
|
ObjectWriter objwriter= objMapper.writer();
|
|
|
|
@Mock
|
|
private TableLoader tLoader;
|
|
|
|
@InjectMocks
|
|
private AlienController aController;
|
|
|
|
Alien alien1 = new Alien(101, "name101");
|
|
Alien alien2 = new Alien(102, "name102");
|
|
Alien alien3 = new Alien(103, "name103");
|
|
|
|
@SuppressWarnings("deprecation")
|
|
@Before
|
|
public void setUp(){
|
|
// initializes object with mock and injectmocks annotation
|
|
MockitoAnnotations.initMocks(this);
|
|
|
|
// builds mockmvc instance for Controller annotation objects
|
|
this.mockMvc=MockMvcBuilders.standaloneSetup(aController).build();
|
|
}
|
|
|
|
@Test
|
|
public void testGetAliens() throws Exception{
|
|
|
|
|
|
|
|
List<Alien> aliens= new ArrayList<>(Arrays.asList(alien1,alien2,alien3));
|
|
|
|
Mockito.when(tLoader.findAll()).thenReturn(aliens);
|
|
|
|
mockMvc.perform(MockMvcRequestBuilders.get("/aliens").
|
|
contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
|
|
.andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(3)) )
|
|
.andExpect(jsonPath("$[2].aname",is("name103") ));
|
|
}
|
|
|
|
@Test
|
|
public void testGetAlienByParam() throws Exception {
|
|
|
|
Mockito.when(tLoader.findById(alien1.getAid())).thenReturn(Optional.ofNullable(alien1));
|
|
|
|
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.get("/alien/101")
|
|
.contentType(MediaType.APPLICATION_JSON);
|
|
|
|
mockMvc.perform(mockRequest).andExpect(status().isOk())
|
|
.andExpect(MockMvcResultMatchers.jsonPath("$", notNullValue()) )
|
|
// ;
|
|
.andExpect(jsonPath("$.aname",is("name101") ));
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
### POST Request Testing
|
|
```java
|
|
@Test
|
|
public void testAddAlien() throws Exception{
|
|
Alien alien = new Alien(101,"hey1");
|
|
|
|
// as insertAlien method of tlLoader s void so no result is expected thats why no when method is used
|
|
|
|
// converting object 'alien' to json
|
|
String alienJSON = objwriter.writeValueAsString(alien);
|
|
|
|
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/alien")
|
|
.contentType(MediaType.APPLICATION_JSON)
|
|
.accept(MediaType.APPLICATION_JSON)
|
|
.content(alienJSON);
|
|
|
|
mockMvc.perform(mockRequest).andExpect(status().isOk())
|
|
.andExpect( jsonPath("$", notNullValue()))
|
|
.andExpect(jsonPath("$.aname", is("hey1")));
|
|
```
|
|
|
|
|
|
### PUT Request Testing
|
|
- when method use equals method to check result so if equals method is not overriden in POJO(Alien class here) then implement it
|
|
- With use of when we can initialize some data too for testing. so if we r checking findByID is returning the record then it means after it checks with mockmvc request , its mock version is implemented too. Without using when if we try to update then it will be treated as new record not updating old one
|
|
```java
|
|
@Test
|
|
public void testUpdateAlien() throws Exception {
|
|
|
|
// to check if equals method is working properly or not
|
|
Alien updatedAlien = new Alien(101,"heyo1");
|
|
String alienJSONTemp = objMapper.writeValueAsString(updatedAlien);
|
|
Alien updatedAlien2 = objMapper.readValue(alienJSONTemp, Alien.class);
|
|
assertEquals(updatedAlien, updatedAlien2);
|
|
|
|
|
|
Alien alien = new Alien(101, "heyo1");
|
|
|
|
Mockito.when(tLoader.findById(alien1.getAid())).thenReturn(Optional.of(alien1));
|
|
Mockito.when(tLoader.saveOrUpdateData(Mockito.eq(alien), Mockito.eq(101))).thenReturn(alien);
|
|
|
|
String alienJSON = objwriter.writeValueAsString(alien);
|
|
|
|
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.put("/aliens/101")
|
|
.contentType(MediaType.APPLICATION_JSON)
|
|
.accept(MediaType.APPLICATION_JSON)
|
|
.content(alienJSON);
|
|
|
|
ResultActions ra =mockMvc.perform(mockRequest).andExpect(status().isOk())
|
|
.andExpect( jsonPath("$", notNullValue()))
|
|
.andExpect(jsonPath("$.aname", is("heyo1")));
|
|
|
|
|
|
// printing response json
|
|
String responseJSON = ra.andReturn().getResponse().getContentAsString();
|
|
System.out.println("resjson: "+responseJSON);
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
Delete request test
|
|
```java
|
|
@Test
|
|
public void testDeleteAlien() throws Exception {
|
|
|
|
|
|
|
|
Mockito.when(tLoader.findById(alien1.getAid())).thenReturn(Optional.of(alien1));
|
|
// Mockito.when(tLoader.deleteById(alien1.getAid())).thenReturn(alien1);
|
|
|
|
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.delete("/alien/101")
|
|
.contentType(MediaType.APPLICATION_JSON);
|
|
|
|
ResultActions ra = mockMvc.perform(mockRequest).andExpect(status().isOk())
|
|
.andExpect(MockMvcResultMatchers.jsonPath("$", notNullValue()) )
|
|
// ;
|
|
.andExpect(jsonPath("$.aname",is("name101") ));
|
|
|
|
// printing response json
|
|
String responseJSON = ra.andReturn().getResponse().getContentAsString();
|
|
System.out.println("resjson: "+responseJSON);
|
|
|
|
|
|
|
|
|
|
}
|
|
``` |