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>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与Hamcrest

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. Mockito

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());
    }


} 

输出

customize userDao.test()
null
passwd
Username was stolen

posted on 2013-07-12 18:38  ZimZz  阅读(2777)  评论(0编辑  收藏  举报