简体   繁体   中英

Using @Autowired for invoking a class to test for a Junit case

@Autowired
BookUtil bookUtil;

@Before
pub void setUp(){
}

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

This gives me a null pointer exception for bookUtil.I am using Junit4 to run this test case in a spring-portlet application.However, if I make the following change ie create the object for the bookUtil manually it works fine.

Make correct use of the the Spring Test Framework , specifically "Dependency Injection of test fixtures" . Ie you need to annotate the class properly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM