1. 程式人生 > 其它 >單元測試使用Mock隨筆

單元測試使用Mock隨筆

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

    @Spy
    @InjectMocks
    private UserServiceImpl userService;
    @Mock
    private UserMapper userMapper;
    @Mock
    private UserAddressService userAddressService;

    @Test
    public void saveOrUpdateTest() {
        try {
            when(userAddressService.check(any())).thenReturn(
true); when(userService.remove(any())).thenReturn(true); doNothing().when(userMapper).setUTF8MB4(); boolean result = userService.saveOrUpdate(null, null); System.out.println(); } catch (Exception ex) { ex.printStackTrace(); } Assert.assertTrue(
true); } }
@InjectMocks:是直接例項化一個物件,且可以實現自動注入,注入的物件就是@Mock或@Spy註解的物件
@Mock:Mock出的物件,執行物件方法會返回Null,可以通過when().thenReturn方式或者doReturn().when().方法的方式指定返回值。
如果物件方法是void的形式的,需要使用doNothing().when形式
@Spy:例項化的物件會優先執行原有方法,如果有類似when return形式的就會得到指定結果。
在MybatisPlus中和
@InjectMocks配合使用,便可實現攔截處理封裝好的this.remove等類似方法