Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring beans testing

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 question is verbose,if anyone have idea please give some hints.

Regards, Raju komaturi

like image 243
Raj Avatar asked Nov 26 '25 10:11

Raj


1 Answers

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");
    }

}
like image 127
Sean Patrick Floyd Avatar answered Nov 28 '25 22:11

Sean Patrick Floyd