通常待測的類不可避免地使用其他類的方法。在不能保證其他類方法正確性的前提下,如何通過單元測試的方式保證待測試的類方法是正確的呢?或者假如待測試的 方法依賴的其他類的代碼還沒有實現而只是定義了接口,那么待測試的方法可以測試呢? 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接口實現類應該返回的數據,從而,我們就可以不需要管它有還是沒有接口的實現類了,類里面有沒有方法了,我們只注重我們當前測試類的邏輯就行了。