Mockito单元测试
ElephantTest 类:
package ut;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
public class ElephantTest {
@Test
public void test_mockito(){
List mockList = mock(List.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getParameter("foo")).thenReturn("boo");
when(mockList.get(0)).thenReturn(1);
Assert.assertEquals("预期返回1",1,mockList.get(0));
}
@Test
public void test_perform() {
Elephant elephant = spy(new Elephant("foo"));
elephant.perform("friday");
verify(elephant).makeNoise();
}
@Test
public void test_not_make_sound_perform(){
Elephant elephant = spy(new Elephant("foo"));
elephant.perform("monday");
then(elephant).should(never()).makeNoise();
}
}
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>myCode</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
</project>
Animal 类:
package ut;
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
}
Elephant类:
package ut;
public class Elephant extends Animal {
public Elephant(String name){
super(name);
}
public void makeNoise(){
System.out.println("elephant make sound");
}
public void perform(String day){
if (day.equals("thursday") || day.equals("friday")){
makeNoise();
}
}
}
|