Spring 3 unit auto-enlargement and testing

My code is:

@Component public class A { @Autowired private B b; public void method() {} } public interface X {...} @Component public class B implements X { ... } 

I want to test in isolation class A. Should I make fun of class B? If so, how? Because it is auto-updated, and there is no setter where I could send a mocking object.

+43
spring junit autowired
Sep 07 '10 at 17:10
source share
4 answers

I want to test in isolation class A.

You should absolutely mock B, and not instantiate and inject instance B. The goal is to check A if B works, so you should not allow potentially damaged B to interfere with A.

However, I highly recommend Mockito . As the mocking framework goes, it is extremely easy to use. You should write something like the following:

 @Test public void testA() { A a = new A(); B b = Mockito.mock(B.class); // create a mock of B Mockito.when(b.getMeaningOfLife()).thenReturn(42); // define mocked behavior of b ReflectionTestUtils.setField(a, "b", b); // inject b into the B attribute of A a.method(); // call whatever asserts you need here } 
+81
Sep 08 '10 at 5:01
source share

Here is an example of how my tests work with Spring 3.1, JUnit 4.7, and Mockito 1.9:

FooService.java

 public class FooService { @Autowired private FooDAO fooDAO; public Foo find(Long id) { return fooDAO.findById(id); } } 

FooDAO.java

 public class FooDAO { public Foo findById(Long id) { /* implementation */ } } 

FooServiceTest.java

 @RunWith(MockitoJUnitRunner.class) public class FooServiceTest { @Mock private FooDAO mockFooDAO; @InjectMocks private FooService fooService = new FooService(); @Test public final void findAll() { Foo foo = new Foo(1L); when(mockFooDAO.findById(foo.getId()).thenReturn(foo); Foo found = fooService.findById(foo.getId()); assertEquals(foo, found); } } 
+18
Jul 23 '12 at 1:40
source share

You can enter the field through reflection using Spring ReflectionTestUtils.setField (or the junit PrivateAccessor ), or you can create the application context and load it. Although for a simple test (non-integration) I prefer to use reflection for simplicity.

+15
Sep 07 '10 at 17:26
source share

This forum discussion makes sense to me. You can declare your private member b as the type of interface B, which is implemented by class B (i.e., Service-oriented), and then declare the class MockB, which also implements the same interface. In the context of the test environment application, you declare the MockB class and the context of your production application, which you declare as the normal class B, and in any case, the code for class A does not need to be changed, since it will be automatically connected.

0
Sep 07 '10 at 17:34
source share



All Articles