[英]Spring: JUnit Testing Rest Controller
I'm trying to test my RestController that is called by an Angular Client.我正在尝试测试由 Angular 客户端调用的 RestController。 My RestController calls a service that communicate through SOAP requests to a Web Service.
我的 RestController 调用通过 SOAP 请求与 Web 服务通信的服务。 Do u have any example to learn from for testing this kind of stuff?
你有什么例子可以学习来测试这种东西吗? Here is my code for BookController :
这是我的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.我想测试对BookClient类执行请求的allBook()函数。
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在我的JUnit 测试类下面
@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.问题是响应的主体始终为空。
Annotate BookClient
with @Profile("!test")
Extend BookClient
as BookClientImpl
(ex.) and annotate it with @Profile("test")
Add @ActiveProfile("test")
to HttpRequestTest
使用
@Profile("!test")
注释BookClient
将BookClient
扩展为BookClientImpl
(例如)并使用@Profile("test")
对其进行注释 将@ActiveProfile("test")
添加到HttpRequestTest
This allow to mock the soap client and to implement a "test" mocked response;这允许模拟soap客户端并实现“测试”模拟响应;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.