首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring WebTestClient bindToController用法

Spring WebTestClient bindToController用法
EN

Stack Overflow用户
提问于 2019-03-11 04:57:22
回答 1查看 2.4K关注 0票数 1

我正在努力弄清楚如何使用WebTestClient.bindToController()。

我有以下两门课:

  • 控制器
  • 服务

Controller.methodx()调用Service.methody()。Service.methody()调用外部REST POST端点。

如何使用WebTestClient.bindToController()来测试这个控制器?我在网上找不到很多使用信息。

主计长:

代码语言:javascript
复制
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CustomerController {

@Autowired
private CustomerService customerService;


@PostMapping(value="/customer", consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Customer> saveCustomer(@RequestBody Customer customer){
    return this.customerService.saveCustomer(customer);
}

服务:

代码语言:javascript
复制
@Service
public class CustomerService implements ICustomerService {


@Autowired  
private WebClient webClient;      


@Override
public Mono<Customer> storeMessage(Customer cust) {

     Mono<Customer> resp = this.webClient.post() 
              .uri("/postdata")
              .body(BodyInserters.fromObject(customer))
              .exchange();

    return resp
}

}

配置:

代码语言:javascript
复制
@Configuration
public class ProdConfig {


@Bean
public ICustomerService getCustomerService() {
    return new CustomerService();
}

@Bean
public WebClient getWebClient() {

    return WebClient.builder()
              .baseUrl("baseurl")
              .defaultHeader(HttpHeaders.CONTENT_TYPE, MIME_TYPE)
              .defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
              .build();
}

}

TestClass:

代码语言:javascript
复制
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = TestConfig.class)
@AutoConfigureMockMvc

public class CustomerControllerTest {

 @MockBean
 private CustomerService customerservice;

 private WebTestClient testClient;

 @Test
 public void testSaveCustomer() throws Exception {       
    testClient= WebTestClient.bindToController(new CustomerController(customerService)).build();

    testClient.post().uri("/customer").body(BodyInserters.fromObject(customer))
            .exchange()
            .expectStatus().is2xxSuccessful();
 }
}

TESTCONFIG:

代码语言:javascript
复制
@Profile("test")
@Configuration
@EnableAutoConfiguration
public class TestConfig {


@Bean
public WebClient getWebClient() {
    return WebClient.builder()
              .baseUrl("baseurl")
              .defaultHeader(HttpHeaders.CONTENT_TYPE, MIME_TYPE)
              .defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
              .build();
}

}

运行测试类时出错:

代码语言:javascript
复制
org.springframework.test.context.TestContextManager[0;39m: Caught exception while invoking 'afterTestMethod' callback on 
TestExecutionListener [org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@61df66b6] for test method 
[public void CustomerControllerTest.testSaveCustomer()] and test instance 
[CustomerControllerTest@22da200e]
java.lang.NoSuchMethodError: org.mockito.MockingDetails.getMockCreationSettings()Lorg/mockito/mock/MockCreationSettings;
    at org.springframework.boot.test.mock.mockito.MockReset.get(MockReset.java:107)
EN

回答 1

Stack Overflow用户

发布于 2019-03-11 06:07:28

WebTestClient内部使用WebClient来执行请求。我们可以简单地将控制器绑定到WebTestClient以处理请求映射,而不是提供发出请求的基url。

CustomerController.java

代码语言:javascript
复制
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CustomerController {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private CustomerService customerService;

    public CustomerController( CustomerService customerService) {
        this.customerService = customerService;
    }

    @PostMapping(value="/customer", consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Mono<Customer> saveCustomer(@RequestBody Customer customer){
        return this.customerService.saveCustomer(customer);
    }

CustomerControllerTest.java

代码语言:javascript
复制
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerControllerRestTest {


    private WebTestClient testClient;

    @MockBean
    private CustomerService customerService;


    @Before
    public void setup() {
        //mock service here
    }



    @Test
    public void  testSaveCustomer() throws Exception {

        Customer customer = new Customer(1L, "test", CustomerGender.MALE);
        testClient= WebTestClient.bindToController(new CustomerController(customerService)).build();

        testClient.post().uri("/customer").body(BodyInserters.fromObject(customer))
                .exchange()
                .expectStatus().is2xxSuccessful();


    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55095444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档