mockito 单元测试

mockito 单元测试

以前写单元测试一般都是用junit写一个@Test而已,后面发现一些功能没法直接使用,依赖于某些环境的时候,这样写就有点力不从心了。

什么是mockito呢?

mockito 是一个Mock框架,mock是一个能够模拟各种对象,然后使其做出你希望的响应。

简单的使用

pom.xml的配置

	<dependency>
		<groupId>org.hamcrest</groupId>
		<artifactId>hamcrest-core</artifactId>
		<version>1.3</version>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.mockito</groupId>
		<artifactId>mockito-core</artifactId>
		<version>1.10.19</version>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.powermock</groupId>
		<artifactId>powermock-api-mockito</artifactId>
		<version>1.6.4</version>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.powermock</groupId>
		<artifactId>powermock-module-junit4</artifactId>
		<version>1.6.4</version>
		<scope>test</scope>
	</dependency>

模拟个对象

//静态导入
import static org.mockito.Mockito.*;

@Test
public void test(){
	
	List<Integer> list=mock(List.class);
	list.add(0);
	when(list.get(0)).equals(0);
	
}


@Test
public void test(){
	List<Integer> list=mock(List.class);
	when(list.get(0)).thenReturn(1);
	Assert.assertSame(1, list.get(0));
	
}

可以看出其可以模拟一个对象,在调用该对象的某个方法是响应你希望的结果。其只可以模拟类的普通方法,对于静态方法的话,得使用PowerMockito这个jar

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticTestUtil.class)
public class PowerMockitoTest1 {

	@Test
	public void test(){
		PowerMockito.mockStatic(StaticTestUtil.class);
		PowerMockito.when(StaticTestUtil.staticTest("SB")).thenReturn("SB");
		
		Assert.assertEquals(StaticTestUtil.staticTest("SB"), "SB");
	}

}

就介绍到这里,具体API可以去看其官网

posted on 2016-04-01 09:53  liaozq  阅读(326)  评论(0编辑  收藏  举报