mockito学习

mockito学习

写一个测试用例,如果在测试类上面添加了注解@RunWith(SpringJUnit4ClassRunner.class),必须添加@ContextConfiguration("/meta/springConfigured.xml")

否则执行测试用例会报错:Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration or @ContextHierarchy.

 

package mockitotest;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import org.mockito.ArgumentMatcher;

import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

public class ArgumentMatchersTest {
    
    @SuppressWarnings("unchecked")
    @Test
    public void test() {
        List mock = mock(List.class);
        when(mock.addAll(argThat(new IsListOfTwoElements()))).thenReturn(true);
        mock.addAll(Arrays.asList("one", "two"));
        verify(mock).addAll(argThat(new IsListOfTwoElements()));
    }
}

class IsListOfTwoElements extends ArgumentMatcher<List<String>> {
       @SuppressWarnings("unchecked")
    public boolean matches(Object list) {
           return ((List<String>) list).size() == 2;
       }
}
View Code

 

package mockitotest;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class MockitoJUnitRunnerAndMockitoAnnotationsTest {

    @Mock
    private List list;

    @Test
    public void shouldDoSomething() {
        list.add(100);
        verify(list).add(200);
    }
}
View Code

 

/**
 * 
 */
package mockitotest;

/**
 * @author Administrator
 *
 */
import static org.mockito.Mockito.*;

import java.util.LinkedList;
import java.util.List;

import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoTest {

    @Test
    public void testMockito_01() {
        // TODO Auto-generated method stub
        List<String> mockedList = mock(List.class);
        mockedList.add("one");
        mockedList.clear();
        verify(mockedList).add("one");
        verify(mockedList).size();
        
    }

    @Test
    public void testMockito_02() {
        //You can mock concrete classes, not only interfaces
        LinkedList mockedList = mock(LinkedList.class);
        //stubbing
        when(mockedList.get(0)).thenReturn("first");
        when(mockedList.get(1)).thenThrow(new RuntimeException());
        //following prints "first"
        System.out.println(mockedList.get(0));
        //following throws runtime exception
        System.out.println(mockedList.get(1));
        //following prints "null" because get(999) was not stubbed
        System.out.println(mockedList.get(999));
        //Although it is possible to verify a stubbed invocation, usually it's just redundant
        //If your code cares what get(0) returns then something else breaks (often before even verify() gets executed).
        //If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
        verify(mockedList).get(0);
    }
    
    @Test
    public void testMockito_03() {
        //You can mock concrete classes, not only interfaces
        LinkedList mockedList = mock(LinkedList.class);
        //stubbing using built-in anyInt() argument matcher
        when(mockedList.get(anyInt())).thenReturn("element");
        //stubbing using hamcrest (let's say isValid() returns your own hamcrest matcher):
        when(mockedList.contains(argThat(isValid()))).thenReturn(true);
        mockedList.contains(5);
        verify(mockedList).contains(argThat(isValid()));
        //following prints "element"
        System.out.println(mockedList.get(999));
        //you can also verify using an argument matcher
        verify(mockedList).get(anyInt());
    }
    
    private  Matcher isValid(){
        class IsNumber extends ArgumentMatcher<Integer> {
            public boolean matches(Object number) {
                   return ((Integer) number)>10;
               }
        }
        return new IsNumber();
    }
    
}
View Code

 

pom.xml文件添加如下依赖

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.8</version>
    <scope>test</scope>
</dependency>

 

如何在spring容器无法找到接口对应的实现类,有一种情况是接口的注解没有加,可以在xml配置文件中添加bean定义,比如

<bean id="productService" class="sardine.commodity.solr.service.impl.ProductServiceImpl"/>

 

@Mock注解的作用和

    <bean id="sendMessage" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="com.som.SendMessage"></constructor-arg>
    </bean>

作用是一样的。

posted @ 2014-10-25 22:17  唾手可得的树  阅读(3910)  评论(1编辑  收藏  举报