模拟问题org.mockito.exceptions.misusing.MissingMethodInitationException

问题描述 投票:0回答:1

我刚刚开始学习 Spring 测试理论,但我不明白如何正确使用模拟 我有两门基础课

@RestController
@RequestMapping("/")
public class MainController {
    @GetMapping("/")
    public String initialPage() {
        return "Hello World";
    }

    @GetMapping("/healthCheck")
    public String healthCheck() {
        Runtime runtime = Runtime.getRuntime();
        if (runtime != null) {
            try {
                long maxMemory = runtime.maxMemory();
                long totalMemory = runtime.totalMemory();
                long freeMemory = runtime.freeMemory();
                return "freeMemory = " + freeMemory;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "OK";
    }
}

并测试一下

@SpringBootTest
public class MainControllerTest {
    @Mock
    private Runtime runtime;
    @Mock
    MainController mainController;

    @Test
    public void testHealthCheck() throws Exception {
        // Create a mock Runtime object

        // Set up the behavior of the mock object
        when(runtime.maxMemory()).thenReturn(100L);
        when(runtime.totalMemory()).thenReturn(50L);
        when(runtime.freeMemory()).thenReturn(25L);

        // Replace the actual Runtime object with the mock object
//        Field runtimeField = MainController.class.getDeclaredField("runtime");
//        runtimeField.setAccessible(true);
//        runtimeField.set(MainController.class, runtimeMock);

        // Call the healthCheck method
        String result = mainController.healthCheck();

        // Assert the result
        assertEquals("freeMemory = 25", result);
    }
}

我尝试使用@InjectMock和@MockBean,但这不起作用。 我对模拟的主要问题是什么,我应该如何正确使用它?

java spring mocking
1个回答
0
投票

Runtime.getRuntime()
是静态方法

参见模拟静态方法

© www.soinside.com 2019 - 2024. All rights reserved.