当前位置 : 主页 > 编程语言 > c++ >

Mockito配合Junit测试

来源:互联网 收集:自由互联 发布时间:2021-06-30
private Person mockPerson = mock(Person.class); import com.sunee.wxsk.dao.PersonDao;import com.sunee.wxsk.domain.Person;import org.junit.Before;import org.junit.Test;import org.mockito.Mock;import org.mockito.MockitoAnnotations;import stati
private Person mockPerson = mock(Person.class);
import com.sunee.wxsk.dao.PersonDao;
import com.sunee.wxsk.domain.Person;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Created by zhanghan on 2017/10/27.
 */
public class CamelTest {
    /*mock模拟类*/
    private Person mockPerson = mock(Person.class);
    /*mock模拟实现接口*/
    private PersonDao mockPersonDao = mock(PersonDao.class);
    /*通过注解方式实现模拟*/
    @Mock
    private PersonDao mockPersonDao2 ;
    /*注解方式实现mock模拟,需要在测试第一步实现初始化*/
    @Before
    public void mockitoInit(){
        /*初始化该测试方法,将所有@Mock标注的对象进行模拟*/
        MockitoAnnotations.initMocks(this);
    }
    /*Mockito配合junit经典测试*/
    @Test
    public void mockitoTest(){
        /*mock场景设定*/
        when(mockPerson.getName()).thenReturn("zhanghan");
        when(mockPersonDao.getPersonByName("tom")).thenReturn(new Person("zhang han",23));
        when(mockPersonDao2.getPerson()).thenReturn(new Person("lily",22));

        /*assert:断言*/
        assertNotNull(mockPersonDao2.getPerson());
        assertEquals(mockPersonDao2.getPerson().getName(),"zhagnhan");
    }
}
网友评论