Spring Junit mock单元测试

2017-07-19  本文已影响0人  康康不遛猫

1、pom.xml引入架包

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

2、spring中使用junit单元测试

测试service层,该方法实现通过项目id去获取项目表的信息,数据库为mysql,Dao层通过mybatis与数据库进行连接。
@RunWith(SpringJUnit4ClassRunner.class) 用于配置spring中测试的环境
@ContextConfiguration(Locations="../*.xml") 用于指定配置文件所在的位置
@Test标注在方法前,表示其是一个测试的方法
Assert 断言,判断实际值与实际值是否一致

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring.xml", "classpath:config/spring-mybatis.xml" })
public class TestProjectService {

    @Autowired(required = true)
    private ProjectNameService projectNameService;

   @Test
    public void testQueryById1() {
        ProjectName projectName = projectNameService.getProjectNameById(1);
        System.out.print(projectName.getProjectname());
        Assert.assertEquals("baseinfo",projectName.getProjectname());
        }
}

3、mock

什么是mock
单元测试:设置测试数据,设定预期结果,验证结果。mock就是创建某类型的虚拟对象,进行模拟操作。

Paste_Image.png
//Person 类
package mockitodemo;  
  
public class Person  
{  
    private final Integer personID;  
    private final String personName;  
    public Person( Integer personID, String personName )  
    {  
        this.personID = personID;  
        this.personName = personName;  
    }  
    public Integer getPersonID()  
    {  
        return personID;  
    }  
    public String getPersonName()  
    {  
        return personName;  
    }  
}

//PersonDao 类 
public interface PersonDao  
{  
    public Person fetchPerson( Integer personID );  
    public void update( Person person );  
}  

//PersonService 类 
public class PersonService  
{  
    private final PersonDao personDao;  
    public PersonService( PersonDao personDao )  
    {  
        this.personDao = personDao;  
    }  
    public boolean update( Integer personId, String name )  
    {  
        Person person = personDao.fetchPerson( personId );  
        if( person != null )  
        {  
            Person updatedPerson = new Person( person.getPersonID(), name );  
            personDao.update( updatedPerson );  
            return true;  
        }  
        else  
        {  
            return false;  
        }  
    }  
}

package mockitodemo;  
  
import org.junit.After;  
import org.junit.AfterClass;  
import org.junit.Before;  
import org.junit.BeforeClass;  
import org.junit.Test;  
import static org.junit.Assert.*;  
import org.mockito.Mock;  
import org.mockito.MockitoAnnotations;  
import org.mockito.ArgumentCaptor;  
import static org.mockito.Mockito.*;  
  
/** 
 * PersonService的单元测试用例 
 * 
 * @author jackzhou 
 */  
public class PersonServiceTest {  
  
    @Mock  
    private PersonDao personDAO;  // 模拟对象  
    private PersonService personService;  // 被测类  
  
    public PersonServiceTest() {  
    }  
  
    @BeforeClass  
    public static void setUpClass() {  
    }  
  
    @AfterClass  
    public static void tearDownClass() {  
    }  
  
    // 在@Test标注的测试方法之前运行  
    @Before  
    public void setUp() throws Exception {  
        // 初始化测试用例类中由Mockito的注解标注的所有模拟对象  
        MockitoAnnotations.initMocks(this);  
        // 用模拟对象创建被测类对象  
        personService = new PersonService(personDAO);  
    }  
  
    //@Ater是在每个测试方法运行完毕后均执行一次
    @After  
    public void tearDown() {  
    }  
  
    @Test  
    public void shouldUpdatePersonName() {  
        Person person = new Person(1, "Phillip");  
        // 设置模拟对象的返回预期值  
        when(personDAO.fetchPerson(1)).thenReturn(person);  
        // 执行测试  
        boolean updated = personService.update(1, "David");  
        // 验证更新是否成功  
        assertTrue(updated);  
        // 验证模拟对象的fetchPerson(1)方法是否被调用了一次  
        verify(personDAO).fetchPerson(1);  
        // 得到一个抓取器  
        ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass(Person.class);  
        // 验证模拟对象的update()是否被调用一次,并抓取调用时传入的参数值  
        verify(personDAO).update(personCaptor.capture());  
        // 获取抓取到的参数值  
        Person updatePerson = personCaptor.getValue();  
        // 验证调用时的参数值  
        assertEquals("David", updatePerson.getPersonName());  
        // asserts that during the test, there are no other calls to the mock object.  
        // 检查模拟对象上是否还有未验证的交互  
        verifyNoMoreInteractions(personDAO);  
    }  
  
    @Test  
    public void shouldNotUpdateIfPersonNotFound() {  
        // 设置模拟对象的返回预期值  
        when(personDAO.fetchPerson(1)).thenReturn(null);  
        // 执行测试  
        boolean updated = personService.update(1, "David");  
        // 验证更新是否失败  
        assertFalse(updated);  
        // 验证模拟对象的fetchPerson(1)方法是否被调用了一次  
        verify(personDAO).fetchPerson(1);  
        // 验证模拟对象是否没有发生任何交互  
        verifyZeroInteractions(personDAO);  
        // 检查模拟对象上是否还有未验证的交互  
        verifyNoMoreInteractions(personDAO);  
    }      
  
    /** 
     * Test of update method, of class PersonService. 
     */  
    @Test  
    public void testUpdate() {  
        System.out.println("update");  
        Integer personId = null;  
        String name = "Phillip";  
        PersonService instance = new PersonService(new PersonDao() {  
  
            @Override  
            public Person fetchPerson(Integer personID) {  
                System.out.println("Not supported yet.");  
                return null;  
            }  
  
            @Override  
            public void update(Person person) {  
                System.out.println("Not supported yet.");  
            }  
        });  
        boolean expResult = false;  
        boolean result = instance.update(personId, name);  
        assertEquals(expResult, result);  
        // TODO review the generated test code and remove the default call to fail.  
        fail("The test case is a prototype.");  
    }  
}     

refer:
http://blog.csdn.net/zhanganbo/article/details/52288080

上一篇下一篇

猜你喜欢

热点阅读