0

我有一个服务类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());
 }

}

4

2 回答 2

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

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

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

于 2012-11-19T15:44:42.043 回答
0

试试这个:

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

另请参阅Spring.IO 文档了解更多详细信息。

于 2012-11-20T05:55:46.707 回答