spring 3 autowiring and junit testing

前端 未结 4 1829
[愿得一人]
[愿得一人] 2020-12-12 17:23

My code:

@Component
public class A {
    @Autowired
    private B b;

    public void method() {}
}

public interface X {...}

@Component
public class B impl         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 17:59

    Here's an example of how I got my tests working 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);
        }
    }
    

提交回复
热议问题