如何使用@Autowired测试服务类

时间:2012-11-19 15:40:15

标签: spring spring-mvc junit spring-test-mvc

我有一个服务类MyService,它被定义并在控制器中使用,如下所示:

public interface MyService {
  public String someMethod() 
}

@Service("myService")
public class MyServiceImpl implements MyService {
  public String someMethod() {
    return "something";
  }
}

@Controller 
public class MyController {
  @Autowired
  public MyService myService;

  @RequestMapping(value="/someurl", method=RequestMethod.GET)
  public String blah () {
    return myService.getsomeMethod();
  }
}

我想为someMethod方法编写测试用例,但是,以下方法不起作用。如何连接实现类?

public class MyServiceImplTest {
 @Autowired
 private MyService myService;

 @Test
 public void testSomeMethod() {
   assertEquals("something", myService.someMethod());
 }

}

2 个答案:

答案 0 :(得分:1)

public class MyServiceImplTest {
    private MyService myService = new MyServiceImpl();

    @Test
    public void testSomeMethod() {
        assertEquals("something", myService.someMethod());
    }
}

为什么要在测试中注入bean而不是自己创建实例?

答案 1 :(得分:0)

试试这个:

@RunWith(SpringJUnit4ClassRunner.class)
 // specifies the Spring configuration to load for this test fixture
@ContextConfiguration("yourapplication-config.xml")

另请参阅the Spring.IO docs了解更多详情。