我不想再使用 powermock 了。因為 junit5 開始模擬靜態類。所以我試圖擺脫 powermock 方法。
當我使用 PowerMock 時,我可以輕松地窺探一個具有私有建構式的類,然后呼叫靜態方法。
這是我的代碼的一部分(當我使用 PowerMock 時)
@RunWith(PowerMockRunner.class)
@PrepareForTest(MessageValidationUtils.class)
public class MessageValidationServiceTest {
@Mock
private CheckpointCustomerService checkpointCustomerService;
@Mock
private ProductClientService productClientService;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
PowerMockito.spy(MessageValidationUtils.class);
}
在我制作了 MessageValidationUtils.class 的間諜物件后,我正在測驗這個:
when(MessageValidationUtils.validateTelegramKeyMap(messageProcessDto.getMessageMessageType(),
messageProcessDto.getMessageKeyValueMap())).thenAnswer((Answer<Boolean>) invocation -> true);
經過一番研究,我找不到任何與監視具有私有建構式和靜態方法的類有關的東西。
uj5u.com熱心網友回復:
在mockStaticMockito 定義期間,您可以指定設定以默認執行實際執行Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS)。這樣,您的靜態模擬將像Spy.
讓我們創建一個簡單Utils的測驗類。
public class Utils {
public static String method1() {
return "Original mehtod1() value";
}
public static String method2() {
return "Original mehtod2() value";
}
public static String method3() {
return method2();
}
}
模擬并method2執行真正的執行method1method3
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class SpyStaticTest {
@Test
public void spy_static_test() {
try (MockedStatic<Utils> utilities = Mockito.mockStatic(Utils.class, Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS))) {
utilities.when(Utils::method2).thenReturn("static mock");
Assertions.assertEquals(Utils.method1(), "Original mehtod1() value");
Assertions.assertEquals(Utils.method2(), "static mock");
Assertions.assertEquals(Utils.method3(), "static mock");
}
}
}
您的班級示例:
@Test
public void test() {
try (MockedStatic<MessageValidationUtils> utilities = Mockito.mockStatic(MessageValidationUtils.class, Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS))) {
utilities.when(() -> MessageValidationUtils.validateTelegramKeyMap(messageProcessDto.getMessageMessageType(),
messageProcessDto.getMessageKeyValueMap())).thenAnswer((Answer<Boolean>) invocation -> true);
//perform testing of your service which uses MessageValidationUtils
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479446.html
