2011-08-31 79 views
3

我有三個豆類,A,B和C.春豆檢測

A類依賴於B類和C類屬性。

我該如何編寫Junit測試用例來測試Class A而不加載Class B和Class C?

我知道這個問題很詳細,如果有人有想法請給點提示。

問候, 拉朱komaturi

回答

5

使用mock框架像EasyMockMockito並注入B和C.

的模擬版本,你或許應該這樣做完全沒有春天,剛剛注入嘲弄編程。

例子:

// Three Interfaces: 
public interface FooService{ 
    String foo(String input); 
} 
public interface BarService{ 
    String bar(String input); 
} 
public interface BazService{ 
    String baz(String input); 
} 

// Implementation for FooService that uses the other two interfaces 
public class FooServiceImpl implements FooService{ 
    public void setBarService(BarService barService){ 
     this.barService = barService; 
    } 
    private BarService barService; 
    public void setBazService(BazService bazService){ 
     this.bazService = bazService; 
    } 
    private BazService bazService; 
    @Override 
    public String foo(String input){ 
     return barService.bar(input)+bazService.baz(input); 
    } 
} 

// And now here's a test for the service implementation with injected mocks 
// that do what we tell them to 
public class FooServiceImplTest{ 

    @Test 
    public void testFoo(){ 
     final FooServiceImpl fsi = new FooServiceImpl(); 

     final BarService barService = EasyMock.createMock(BarService.class); 
     EasyMock.expect(barService.bar("foo")).andReturn("bar"); 
     fsi.setBarService(barService); 

     final BazService bazService = EasyMock.createMock(BazService.class); 
     EasyMock.expect(bazService.baz("foo")).andReturn("baz"); 
     fsi.setBazService(bazService); 

     EasyMock.replay(barService, bazService); 

     assertEquals(fsi.foo("foo"), "barbaz"); 
    } 

} 
+0

謝謝,請您提供任何例子。 – Raj

+0

@Raju當然,在這裏 –