我有三个Java Bean类,A、B和C。
类A依赖于类B和类C的属性。
如何编写Junit测试用例来测试类A,而不载入类B和类C?
我知道这个问题很啰嗦,如果有人有想法,请给一些提示。
祝好,
Raju komaturi
类A依赖于类B和类C的属性。
如何编写Junit测试用例来测试类A,而不载入类B和类C?
我知道这个问题很啰嗦,如果有人有想法,请给一些提示。
祝好,
Raju komaturi
使用类似于EasyMock或Mockito的模拟框架,并注入B和C的模拟版本。
最好完全不使用Spring,只在程序中以编程方式注入模拟对象。
示例:
// 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");
}
}