开发者

Spring beans testing

开发者 https://www.devze.com 2023-04-01 05:16 出处:网络
I have three bean classes,A,B and C. Class A depends onclass B and Class C properties. How can i write Junittest case to test the Class A without loading Class B and Class C?

I have three bean classes,A,B and C.

Class A depends on class B and Class C properties.

How can i write Junit test case to test the Class A without loading Class B and Class C?

I know this que开发者_StackOverflowstion is verbose,if anyone have idea please give some hints.

Regards, Raju komaturi


Use a Mock framework like EasyMock or Mockito and inject mock versions of B and C.

You should probably do that completely without Spring, just inject the Mocks programmatically.

Example:

// 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

精彩评论

暂无评论...
验证码 换一张
取 消