junit various
Test target example YellowServiceImpl
① DeclaredField
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 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