JMock+Junit4结合完成TDD实例

通常待测的类不可避免地使用其他类的方法。在不能保证其他类方法正确性的前提下,如何通过单元测试的方式保证待测试的类方法是正确的呢?或者假如待测试的 方法依赖的其他类的代码还没有实现而只是定义了接口,那么待测试的方法可以测试呢? JMock 的出现解决了上面的问题。JMock 提供给开发者切断待测方法对其他类依赖的能力,使开发者能够将全部的注意力都集中于待测方法的逻辑上,而不用担心其他类方法是否能够返回正确的结果。这样 的测试更具有针对性,更容易定位到潜在问题。

首先,我们要准备好所依赖的包:

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jmock</groupId>
            <artifactId>jmock-junit4</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.jmock</groupId>
            <artifactId>jmock</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.jmock</groupId>
            <artifactId>jmock-legacy</artifactId>
            <version>2.8.1</version>
        </dependency>
    </dependencies>

下面我们来写一个实例:

1.首先,我们先写一个接口类:

package jmust.demo.Cobertura.Inter;

public interface IMathfun {

    public int abs(int num);
}

2.接着,我们写一个普普通通的方法类,注意,该方法类并不实现上面的接口:

package jmust.demo.Cobertura.Service;

import jmust.demo.Cobertura.Inter.IMathfun;

public class TestJunit4 {
    private IMathfun util;

    public TestJunit4(IMathfun util) {
        this.util = util;
    }

    public int cal(int num) {
        return 10 * util.abs(num);
    }
}

到这里,我们可以发现,上面的接口并没有实现类,在这里,我们会想,实现类都没有,那么我们该如何去单元测试呢?岂不是断掉了?是的,确实是断掉了,那怎么办呢?还有没有方法可以实现断掉了也可以测试呢?答案是肯定的,下面我们就引用JMock来实现这个断掉的测试。

3.最后,我们来建一个测试类:

package jmust.demo.CoberturaTest;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import jmust.demo.Cobertura.Inter.IMathfun;
import jmust.demo.Cobertura.Service.TestJunit4;
import junit.framework.TestCase;

public class Junit4Test extends TestCase{
    private Mockery context = new JUnit4Mockery();
    private IMathfun math = null;
    private TestJunit4 test = null;
    
    @Before
    public void setUp() throws Exception{
        super.setUp();
        math = context.mock(IMathfun.class);
        test = new TestJunit4(math);
        context.checking(new Expectations(){ 
              { 
                  exactly(1).of(math).abs(-20);will(returnValue(20)); 
              } 
        }); 
        
    }
    
    @After
    public void setDown(){
        
    }
    @Test
    public void test(){
        assertEquals(200, test.cal(-20));
    }
}

就这样,我们就实现了断掉也可以单元测试,叫做mock接口实现类应该返回的数据,从而,我们就可以不需要管它有还是没有接口的实现类了,类里面有没有方法了,我们只注重我们当前测试类的逻辑就行了。

原文地址:https://www.cnblogs.com/lvk618/p/5002835.html