[JAVA] Junit

junit divers

Exemple de cible de test YellowServiceImpl ① DeclaredField La source @Autowired(required = true) @Named("nameList") private List nameList;

junit:

@PrepareForTest({YellowServiceImpl.class, NameChecker.class}) public class YellowServiceImplTest {

@InjectMocks private YellowServiceImpl yellowServiceImpl;

List nameList = new ArrayList(); nameList.add("hanmeimei"); nameList.add("lilei");

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

Recommended Posts

Junit
JUnit 4 notes
Mémorandum JUnit
Refactoring dans JUnit
Notes d'utilisation de JUnit5
Lancement du test JUnit essayez quelque chose
Migrer de JUnit 4 vers JUnit 5
Mémo simple de JUnit de java
Faites un test unitaire avec Junit.