Spring 如何使用@Autowired测试服务类
我有一个服务类Spring 如何使用@Autowired测试服务类,spring,spring-mvc,junit,spring-test-mvc,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 cl
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());
}
}
为什么要在测试中注入bean而不是自己创建实例?尝试以下方法:
@RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("yourapplication-config.xml")
有关更多详细信息,请参见
@RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("yourapplication-config.xml")