如何用Mockito和JUnit编写测试,确保长尾词查询功能正确?
- 内容介绍
- 文章标签
- 相关推荐
本文共计180个文字,预计阅读时间需要1分钟。
java使用Mockito进行Person类的单元测试,创建一个mock对象并注入到PersonDao中。
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"); } }
本文共计180个文字,预计阅读时间需要1分钟。
java使用Mockito进行Person类的单元测试,创建一个mock对象并注入到PersonDao中。
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"); } }

