Spring Bean测试

3
我有三个Java Bean类,A、B和C。
类A依赖于类B和类C的属性。
如何编写Junit测试用例来测试类A,而不载入类B和类C?
我知道这个问题很啰嗦,如果有人有想法,请给一些提示。
祝好,
Raju komaturi
1个回答

5

使用类似于EasyMockMockito的模拟框架,并注入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");
    }

}

谢谢,你能提供任何例子吗? - Raj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接