简体   繁体   中英

How to create a unit test for a GET Rest service (Spring)

I developed an application which stores Books in MongoDb and the data is obtained from the console from the user and it's directly saved to MongoDb. And all the details of the Book objects are passed to the Angular frontend and I've used Spring to make the api.

@RestController
@RequestMapping("/api")
public class Controller {

@Autowired
    BookRepository bookRepo;

@GetMapping("/books")
    public List<Book> getBooks(){
        return bookRepo.findAll();
    }
}

The API is working without any error.(Checked using postman and data can be viewed from the Angular site)
Now I have to write a unit test for this Controller class. My knowledge on testing is very low please help me with this. Thanks in advance.

You can try the below code for your unit testing.

@RunWith(MockitoJUnitRunner.class)
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;
    
    @InjectMocks
    private Controller controller;
    
    @Mock
    BookRepository bookRepo;
    
    @Before
    public void Setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }
    
    @Test
    public void testGetBooks(){
    
        Book book1 = new Book();
        book1.setBookId(101L);
        
        Book book2 = new Book();
        book2.setBookId(102L);
    
        List<Book> books = new ArrayList<>();
        books.add(book1);
        books.add(book2);
    
        Mockito.when(bookRepo.findAll()).thenReturn(books);
        
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/books")
                .accept(MediaType.APPLICATION_JSON);
                
        mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk());
        
        Mockito.verify(bookRepo, times(1)).findAll();   
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM