mock静态方法,使用restassuredmockmvc实现spring云契约

fjnneemd  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(401)

我一直试图在生产者端模拟一个静态方法来生成和运行针对控制器的契约,但是测试是针对实际方法运行的
这里是producer上的控制器,其中“getid”是类中的静态方法

@PostMapping(path = "/getone", consumes = "application/json", produces = "application/json")
public ResponseEntity<Response> getone(@RequestBody Test[] test) {
    String appId = Utils.getId();
    return new ResponseEntity<>(service.pub(test,id), HttpStatus.OK);
}

下面是在生产者方面生成合同的基本测试

@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@SpringBootTest
public class ContractTest {

    @Autowired
    private WebApplicationContext context;

    @Mock
    private Utils utils;

    @BeforeEach
    void setup() {
        try (MockedStatic mocked = mockStatic(Utils.class)) {
            mocked.when(() -> Utils.getId()).thenReturn("194");
            RestAssuredMockMvc.webAppContextSetup(this.context);}
    }

我也尝试过使用独立的设置,但是没有成功

@Autowired
    private ApiController controller;

  @BeforeEach
    void setup() {
        try (MockedStatic mocked = mockStatic(Utils.class)) {
            mocked.when(() -> Utils.getId()).thenReturn("194");
        StandaloneMockMvcBuilder standaloneMockMvcBuilder = MockMvcBuilders.standaloneSetup(controller);
         RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder);}

测试是针对实际类而不是模拟值运行的。有没有办法模拟静态方法getid()并生成测试?

xxb16uws

xxb16uws1#

你能试着换一下这条线吗

try (MockedStatic mocked = mockStatic(Utils.class)) {

try (MockedStatic<Utils> mocked = mockStatic(Utils.class)) {

相关问题