本文共 3631 字,大约阅读时间需要 12 分钟。
repositories { jcenter() }dependencies { testCompile "org.mockito:mockito-core:1.+" }
apply plugin: 'java'apply plugin: 'idea'sourceCompatibility = 1.5version = '1.0'repositories { mavenCentral() jcenter()}dependencies { testCompile group: 'junit', name: 'junit', version: '4.11' testCompile "org.mockito:mockito-core:1.8.5"}
package com.mengdd.examples.mockito;public class HelloWorld { private MyRobot mRobot; public MyRobot getRobot() { return mRobot; } public void setRobot(MyRobot robot) { this.mRobot = robot; } /** * This is the method we want to test. * When there is an robot, this method return the robot's information * otherwise, return some sorry text */ public String sayHello() { MyRobot robot = getRobot(); if (null != robot) { return robot.getSomeInfo(); } return "No robot here, sorry!"; } /** * MyRobot class */ public static class MyRobot { /** * Get some information from somewhere, the implementation may varies */ public String getSomeInfo() { return "Hello World -- From robot"; } }}
package com.mengdd.examples.mockito;import org.junit.Test;import static org.hamcrest.CoreMatchers.is;import static org.junit.Assert.assertThat;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;public class HelloWorldTest { @Test public void testSayHelloWhenThereIsRobot() throws Exception { // We want to test the sayHello() method in the class HelloWorld. // But we don't care about how MyRobot get its information.(We can treat it as external interface). // Maybe the robot rely on many complicated things.(Although it's simple in this case.) // And when the robot's actions change in the future, we don't need to change this test case. // We can mock the MyRobot's action to make it simple and just test whether sayHello() can do its own work. // Mock steps HelloWorld.MyRobot robot = mock(HelloWorld.MyRobot.class); // Mock MyRobot class String mockInfo = "some mock info"; when(robot.getSomeInfo()).thenReturn(mockInfo); // Set behavior for mock object // real object HelloWorld helloWorld = new HelloWorld();//This is the real objec we want to test helloWorld.setRobot(robot);//set the mock robot to real object // execute the target method we want to test String result = helloWorld.sayHello(); // assert the result is what we want to have assertThat(result, is(mockInfo)); }}
@Testpublic void testSayHelloWhenThereIsNoRobot() throws Exception { HelloWorld helloWorld = new HelloWorld(); helloWorld.setRobot(null); String result = helloWorld.sayHello(); assertThat(result, is("No robot here, sorry!"));}
转载地址:http://bpqyz.baihongyu.com/