vendredi 28 août 2020

Spring: JUnit Testing Rest Controller

I'm trying to test my RestController that is called by an Angular Client. My RestController calls a service that communicate through SOAP requests to a Web Service. Do u have any example to learn from for testing this kind of stuff? Here is my code for BookController:

@RepositoryRestController  
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class BookController {
    @Autowired BookClient quoteClient;
    GetBookListResponse lista = new GetBookListResponse();
    BookService bookservice = new BookService();
  
    @GetMapping(value = "/books")
    public Object[] allBooks() {
        lista = quoteClient.getBookList(true);
        return lista.getBookList().toArray();
        
    }

I would like to test allBook() function that perform a request to the BookClient class.

public class BookClient extends WebServiceGatewaySupport {
public GetBookListResponse getBookList(boolean richiesta) {

        GetBookListRequest request = new GetBookListRequest();
        
        request.setRichiesta(true);
        log.info("Getting all books: ");
        
        try {
            GetBookListResponse response = (GetBookListResponse) getWebServiceTemplate()
            .marshalSendAndReceive("http://localhost:8080/ws/book", request,
                new SoapActionCallback(
                    "http://spring.io/guides/gs-producing-web-service/GetBookListRequest"));

        return response;
        } catch (Exception ex) {
            throw ex;}
        }

Below my JUnit testing class

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest(value = BookController.class,  excludeAutoConfiguration = {SecurityAutoConfiguration.class})
public class HttpRequestTest {


    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private BookController controller;
    @MockBean
    private BookClient client;
    
    
    
    @Before
      public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
      }
    
    
    
    @Test
    @WithMockUser(username = "admin", password = "mypass", roles="ADMIN")
    public void allBookShouldWork() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/books"))
                .andExpect(MockMvcResultMatchers.status().isOk()).andDo(print()).andReturn();
        
        assertThat(mvcResult.getResponse().getContentAsString()).isNotNull();
        
    }

The problem is that the body of the response is always null.

Aucun commentaire:

Enregistrer un commentaire