0

I've been trying to mock a static method on the producer side to generate and run the contracts against the controller but the tests are running against the actual method

Here's the controller on producer where "getId" is the static method in the class

 @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);
}

Here's the base test on the producer side which generates contracts

@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);}
    }

I've tried using the standalone setup as well but no luck

 @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);}

The tests are running against the actual class rather than the mocked value. Is there any way to mock the static method getId() and generate the tests ?

sn879
  • 173
  • 3
  • 12

1 Answers1

0

Can you try replacing this line:

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

To

try (MockedStatic<Utils> mocked = mockStatic(Utils.class)) {
Steephen
  • 14,645
  • 7
  • 40
  • 47
  • Hey @Steephen, thanks for the response but it didn't work – sn879 Nov 15 '20 at 20:23
  • @sn879 Can you remove `@Mock private Utils utils;` this line from your test class along with above changes – Steephen Nov 15 '20 at 20:33
  • I think its an unused dependency that I just copied over but I tried removing that and rerun the tests and it's calling the actual method rather than the mock – sn879 Nov 15 '20 at 20:39