I have a test which is getting an error while integrating the static mock.
org.powermock.api.mockito.ClassNotPreparedException:
[Ljava.lang.Object;@76304b46
The class com.sda.helper.IbanUtil not prepared for test.
My test code:
package ***;
import ***
@RunWith(PowerMockRunner.class)
@PrepareForTest({IbanUtil.class, BlackListCheckServiceImpl.class})
@ExtendWith(MockitoExtension.class)
class BlackListCheckServiceImplTest {
@Mock
private BlacklistUtil blacklistUtil;
@InjectMocks
private BlackListCheckServiceImpl blackListCheckService;
String validIban = "validIban";
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testCheckBlacklistInfo_ValidIban_NotInBlacklist() throws Exception {
Class<?> clazz = BlackListCheckServiceImpl.class;
Method method = clazz.getDeclaredMethod("isBlacklistedIban", String.class);
method.setAccessible(true);
when(method.invoke(blackListCheckService, validIban)).thenReturn(false);
mockStatic(IbanUtil.class, Mockito.CALLS_REAL_METHODS);
PowerMockito.doNothing().when(IbanUtil.class, "validate", "ValidIBAN123");
// Act
boolean result = blackListCheckService.checkBlacklistInfo(validIban);
// Assert
assertFalse(result);
}
@Test
void testCheckBlacklistInfo_ValidIban_InBlacklist_throwsException() throws Exception {
Class<?> clazz = BlackListCheckServiceImpl.class;
Method method = clazz.getDeclaredMethod("isBlacklistedIban", String.class);
method.setAccessible(true);
when(method.invoke(blackListCheckService, validIban)).thenReturn(true);
// Act
boolean result = blackListCheckService.checkBlacklistInfo(validIban);
// Assert
assertTrue(result);
}
}
Mock dependencies:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
Although I integrated the
@PrepareForTest({IbanUtil.class, BlackListCheckServiceImpl.class})
Why it is still getting an error?
You are mixing junit5 (called 'jupiter) and junit4, that will go wrong. Your test runner will do nothing with annotations it does not understand.
Stick with one of them. Choose junit5 unless you have existing test-code that cant be ported to junit4 for some reason.
With junit5 you can mock static methods with mockito (version 3.4 and up) directly, you do not need to use PowerMock for this any more, see this answer: https://stackoverflow.com/a/63920995/7465516
With junit4, you can use the PowerMock-library. You will have to drop the
ExtendWithannotation you have though - that is for junit5. Also, PowerMock and Mockito are different libraries. Your PowerMock-test does not need Mockito.