Junit Hamcrest Mockito單元測試

pom.xml配置java

<?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>TestPractice</groupId>
    <artifactId>TestPractice</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    
</project>

 

1. Junit與Hamcrestapache

package com.test.foo;

public class Foo {
    public String concat(String s1, String s2) {
        if (s1 == null) return s2;
        return s1 + s2;
    }
}

package com.test.foo;

import org.hamcrest.Matcher;
import org.junit.*;

import java.util.ArrayList;
import java.util.List;

import static junit.framework.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assume.assumeThat;
import static org.mockito.Matchers.contains;
import static org.mockito.Mockito.when;

public class FooTest {
    private Foo foo;

    /**
     * @BeforeClass @AfterClass 設置在public 靜態方法之上,表示在class加載以前執行。
     * 這樣設置的方法只會執行一次。而@Before @After則會再每次test以前/以後執行
     */
    @Before
    public void setUp() {
        foo = new Foo();
    }

    /**
     * Ignore標籤表示忽略次測試
     */
    @Test
    public void concatTwoSubstringFirstIsNull() {
        String actual = foo.concat(null, "s2");

        String expected = "s2";
        Assert.assertEquals(expected, actual);
    }

    // expected表示指望值
    @Test(expected = RuntimeException.class)
    public void testException() {
        throw new RuntimeException();
    }

    /**
     * Hamcrest方法測試
     */
    @Test
    @Ignore
    public void testHamcrest() {
        int i = 10;
        assumeThat(i, is(10));  // 前置條件,若是不知足,則不執行後置代碼
        List<String> list = new ArrayList<String>();
        list.add("s1");
        list.add("s2");

        assertTrue(list.contains("s5"));

        // hamcrest的assertThat能夠直接對list進行判斷
        assertThat(list, hasItem("s5"));
    }

    /**
     * Mockito方法測試
     */
//    public void testMock() {
//        Man mockMan = mock(man);
//        // 當真的執行到save方法時,會比對實際參數和expectedMan的符合程度,而後返回true 發了塞
//     when(mockMan.save(expectedMan)).thenReturn(true);
//    }


    @After
    public void tearDown() {
        foo = null;
    }
}

 

2. Mockitomaven

package com.test.foo.model;

public class User {
    private String username;
    private String passwd;

    public User(String username, String passwd) {
        this.username = username;
        this.passwd = passwd;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof User))
            return false;
        User user = (User) o;
        return username.equals(user.getUsername())
                && passwd.equals(user.getPasswd());
    }
}


package com.test.foo.dao;

import com.test.foo.model.User;

public class UserDAO {
    public  void saveUser(User user) {}

    public String test() {
        return "Original methods";
    }
}


package com.test.foo.service;

import com.test.foo.dao.UserDAO;
import com.test.foo.model.User;

public class UserService {
    UserDAO userDao;

    public void saveUser(User user) {
        userDao.saveUser(user);
    }


    public UserDAO getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDAO userDao) {
        this.userDao = userDao;
    }
}

package com.test.foo.service; 

import com.test.foo.dao.UserDAO;
import com.test.foo.model.User;
import org.junit.Test;
import org.junit.Before; 
import org.junit.After;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import javax.annotation.Resource;

import static org.mockito.Mockito.*;

/** 
* UserService Tester. 
* 
* @author <Authors name> 
* @since <pre>Jul 12, 2013</pre> 
* @version 1.0 
*/ 
public class UserServiceTest {
    // 自動mock注入
    @InjectMocks
    @Resource(name="userService")
    private UserService userService;

    // mock對象,實際上mock對象裏面的方法都已經置空,咱們須要掌握的是他執行方法的時機
    // 以及執行方法時的參數
    @Mock
    private UserDAO userDao;

    @Before
    public void before() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @After
    public void after() throws Exception {
    }

    /**
    *
    * Method: saveUser(User user)
    *
    */
    @Test
    public void testSaveUser() throws Exception {
        User user = new User("username2", "passwd");
        User expectUser = new User("username", "passwd");
        // 測試void方法使用doThrow,當調用saveUser()並且,user和expectUser相同時,則會拋出異常,以此檢查傳入的User是否正確
        doThrow(new RuntimeException()).when(userDao).saveUser(expectUser);
        userDao.saveUser(user);
        // 定製方法返回值
        when(userDao.test()).thenReturn("customize userDao.test()");
        System.out.println(userDao.test());

        // 重置方法
        Mockito.reset(userDao);
        System.out.println(userDao.test());

        // 將一個對象變爲Spy對象,他的做用是讓這個對象在保持原功能的基礎上接受監視
        User spy = Mockito.spy(user);
        System.out.println(spy.getPasswd());
        when(spy.getPasswd()).thenReturn("Passwd was stolen");
        System.out.println(spy.getPasswd());
    }


} 

輸出ide

customize userDao.test()
null
passwd
Username was stolen測試

相關文章
相關標籤/搜索