junit

junit various

Test target example YellowServiceImpl ① DeclaredField 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 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 Source PropertyUtil.getProperty("name"); junit:

import static org.powermock.api.mockito.PowerMockito.mockStatic; mockStatic(PropertyUtil.class); when(PropertyUtil.getProperty(NAME)).thenReturn("HANMEIMEI");

④private method 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) {

// (Check parameters for TestClass.testMethodName assertTrue(StringUtils.equals("expectString", (String) invocationOnMock.getArgument(2))); return null; } });

// Test run target.excute(param); } catch (Exception e) { fail(); }

Recommended Posts

junit
JUnit 4 notes
JUnit memorandum
[100%] CyclicRotation (src & jUnit)
[100%] FrogJmp (src & jUnit)
[100%] FrogRiverOne (src & jUnit)
[100%] OddOccurrencesInArray (src & jUnit)
[100%] MinAvgTwoSlice (src & junit)
[100%] PassingCars (src & junit)
Refactoring in JUnit
[100%] PermCheck (src & junit)
[100%] TapeEquilibrium (src & jUnit)
[100%] MaxProductOfThree (src & jUnit)
JUnit5 usage memo
[100%] BinaryGap (src & jUnit)
Try JUnit test launch
Migrate from JUnit 4 to JUnit 5
Java JUnit brief note
How to use JUnit 5
Unit test with Junit.