junit divers
Exemple de cible de test YellowServiceImpl
① DeclaredField
La source
@Autowired(required = true)
@Named("nameList")
private List
junit:
@PrepareForTest({YellowServiceImpl.class, NameChecker.class}) public class YellowServiceImplTest {
@InjectMocks private YellowServiceImpl yellowServiceImpl;
List
Field field2 = YellowServiceImpl.class.getDeclaredField("nameList"); field2.setAccessible(true); field2.set(yellowServiceImpl, nameList);
②inject interface La source:
@Inject NameChecker nameChecker;
nameChecker.getResult(testList);
junit: import static org.mockito.ArgumentMatchers.any; @RunWith(PowerMockRunner.class) @PrepareForTest({ NameChecker.class}) public class SometingImplTest {
@Mock NameChecker nameChecker;
PowerMockito.when(nameChecker, "getResult", any()) .thenReturn("somthing");
③static method La source PropertyUtil.getProperty("name"); junit:
import static org.powermock.api.mockito.PowerMockito.mockStatic; mockStatic(PropertyUtil.class); when(PropertyUtil.getProperty(NAME)).thenReturn("HANMEIMEI");
④private method La source: private String getName(String id){
} junit: import java.lang.reflect.Field; import java.lang.reflect.Method;
Method method = YellowServiceImpl.class.getDeclaredMethod("getName", String.class); method.setAccessible(true); //test class, method parameter method.invoke(yellowServiceImpl, "HanMeimei");
⑤ the sample of verify the parameter of static void method
import static org.mockito.ArgumentMatchers.any; @RunWith(PowerMockRunner.class) @PrepareForTest({ TestClass.class })
mockStatic(TestClass.class);
try {
PowerMockito.when(TestClass.class, "testMethodName", any(), any(), any())
.thenAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) {
// (Vérifiez les paramètres pour TestClass.testMethodName assertTrue(StringUtils.equals("expectString", (String) invocationOnMock.getArgument(2))); return null; } });
// Essai target.excute(param); } catch (Exception e) { fail(); }