Maven簡單的配置Junit測試及使用簡單的mock

一、maven依賴配置以下apache

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <appendAssemblyId>false</appendAssemblyId>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>RunJob</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>assembly</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.5</version>
            </plugin>
        </plugins>
    </build>

 

 

二、編寫測試代碼app

public class SimpleTest {
    @Test
    public void test() {
        Assert.assertTrue("a".equals("a"));
    }

    @Test
    public void testMock() {
        List m = mock(List.class);
        m.add(1);
        m.clear();

        verify(m).add(1);//驗證執行過add(1)操做
        verify(m).clear();//驗證執行過clear操做
    }

    @Test
    public void when_thenReturn() {
        //mock一個Iterator類
        Iterator iterator = mock(Iterator.class);
        //預設當iterator調用next()時第一次返回hello,第n次都返回world
        when(iterator.next()).thenReturn("hello").thenReturn("world");
        //使用mock的對象
        String result = iterator.next() + " " + iterator.next() + " " + iterator.next();
        //驗證結果
        assertEquals("hello world world", result);
    }
}
相關文章
相關標籤/搜索