我有三个bean类,A,B和C.
A类取决于B类和C类属性。
如何在不加载B类和C类的情况下编写Junit测试用例来测试A类?
我知道这个问题很冗长,如果有人有想法请提供一些提示。
此致 Raju komaturi
答案 0 :(得分:5)
使用像EasyMock或Mockito这样的模拟框架,并注入B和C的模拟版本。
如果没有Spring,你应该完全这样做,只需以编程方式注入Mocks。
示例:强>
// 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");
}
}