【问题标题】:Using @Autowired for invoking a class to test for a Junit case使用 @Autowired 调用一个类来测试一个 Junit 案例
【发布时间】:2011-12-28 10:31:25
【问题描述】:
@Autowired
BookUtil bookUtil;

@Before
pub void setUp(){
}

@Test
pub void testLogin(){
String userName = "Harry";
String password = "1234";
bookUtil = new BookUtil();
bookUtil.checkuserNamePassword (userName, password);
}

这给了我 bookUtil 的空指针异常。我正在使用 Junit4 在 spring-portlet 应用程序中运行这个测试用例。但是,如果我进行以下更改,即手动为 bookUtil 创建对象,它可以正常工作。

【问题讨论】:

  • 向我们展示整个类,而不仅仅是方法和字段
  • 另外,我想查看您注册 bookUtil bean 的 bean 配置文件,或者如果它是组件(自动扫描)或 Javaconfig 代码,则它是类。

标签: java spring junit junit4


【解决方案1】:

正确使用Spring Test Framework,特别是"Dependency Injection of test fixtures"。 IE。您需要正确注释类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("your-context.xml")
class MyTest {
    @Autowired
    BookUtil bookUtil;
    ...
}

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多