Mockito常用的三种方式

依赖的jar包。

       
            junit
            junit
            4.12
            test
        
        
            org.mockito
            mockito-all
            1.10.19
            test
        

        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        

第一种方式:

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {

    private UserDao userDao;
    private UserServiceImpl userServiceImpl;
    private RegisterController registerController;
    private HttpServletRequest request;

       @Before
       public void init(){
           this.request = mock(HttpServletRequest.class);
           this.userDao = mock(UserDao.class);
           this.userServiceImpl = new UserServiceImpl(userDao);
           this.registerController = new RegisterController(userServiceImpl);

       }

注解的方式:

public class MockitoAnnotationTest {

    @Mock
    private UserDao userDao;
    @Mock
    private HttpServletRequest request;
    private UserServiceImpl userServiceImpl;
    private RegisterController registerController;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        this.userServiceImpl = new UserServiceImpl(userDao);
        this.registerController = new RegisterController(userServiceImpl);
    }

@Rule的方式:

public class MockitoRuleTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    private UserDao userDao;
    @Mock
    private HttpServletRequest request;
    private UserServiceImpl userServiceImpl;
    private RegisterController registerController;

    @Before
    public void init() {
        this.userServiceImpl = new UserServiceImpl(userDao);
        this.registerController = new RegisterController(userServiceImpl);
    }

你可能感兴趣的:(Mockito常用的三种方式)