2

我正在为 spring 3 restful 服务编写 junit 测试用例。当我尝试将它作为 junit 执行时,我将 JdbcTemplate 设为 null。我不确定我在哪里做错了。请帮我摆脱这个...

LoginServiceImpl.java 文件,

private NamedParameterJdbcTemplate jdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    System.out.println("--------------"+jdbcTemplate.toString());
}

private static Map<String, AuthToken> tokenHash = new ConcurrentHashMap<String, AuthToken>();

private static String authTokenDetailsSql = "select * from authtoken where token = :token";

@Override
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public ServiceBean newAccount(@RequestBody Registration registration) {
    String newAccountSql = "INSERT INTO account (email,password,name) VALUES (:email,:password,:name)";
    ServiceDataBean<AuthToken> retBean = new ServiceDataBean<AuthToken>();
    try {
        System.out.println("register service calling.....");
        MapSqlParameterSource namedParameters = new MapSqlParameterSource();
        namedParameters.addValue("email", registration.getEmail());
        messageDigest = MessageDigest.getInstance("MD5");
        byte[] md5 = new byte[64];
        messageDigest.update(registration.getPassword().getBytes("iso-8859-1"), 0, registration.getPassword().length());
        md5 = messageDigest.digest();
        namedParameters.addValue("password", convertedToHex(md5));
        namedParameters.addValue("name", registration.getName());
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();

        // TODO what to do with the updInt also check it's not -1
        int updInt = jdbcTemplate.update(newAccountSql, namedParameters, generatedKeyHolder);
        long accountId = (Long) generatedKeyHolder.getKeys().get("GENERATED_KEY");
        registration.getDevice().setOwner(registration.getId());
        fotoframz.register(registration.getDevice());
        Login login = new Login();
        login.setEmail(registration.getEmail());
        login.setPassword(registration.getPassword());
        login.setDevice(registration.getDevice());
        retBean = (ServiceDataBean<AuthToken>) this.login(login);
        System.out.println("form register");
    } catch (Throwable e) {
        retBean.setStatusCode("001");
        e.printStackTrace();
    }
    return retBean;
}

我得到 jdbctemplate=null 在int updInt = jdbcTemplate.update(newAccountSql, namedParameters, generatedKeyHolder);

我的 applicationContext-test.xml 文件位于 src/test/resources 文件夹中..applicationContext-test.xml 文件

<context:component-scan base-package="net.mss.ff.services" />       
<context:property-placeholder location="classpath:/app.properties" />

<!-- <task:annotation-driven /> -->
<context:annotation-config />
<!-- <import resource="apicontroller_v1-servlet.xml"/>
<import resource="applicationContext.xml"/> -->

<bean id="photoService" class="net.mss.ff.services.core.api.impl.PhotoServiceImpl">
    <property name="rootStorageFolder" value="${storage.root}" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

LoginServiceImplTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext-test.xml"})
public class LoginServiceImplTest {

LoginServiceImpl loginServiceObj = new LoginServiceImpl();
Device deviceMock;

@Autowired
private Fotoframz fotoframz;

/*private NamedParameterJdbcTemplate jdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}*/

@Before
public void setUp() throws Exception {
    //loginServiceObj = new LoginServiceImpl();
}

@After
public void tearDown() throws Exception{

}

/**
 * Test method for {@link net.mss.ff.services.core.api.impl.LoginServiceImpl#newAccount(net.mss.ff.services.core.beans.Registration)}.
 */
@Test
public void testNewAccount() {
    Registration mockRegObj = new Registration();
    deviceMock = new Device();
    deviceMock.setActive(false);
    deviceMock.setHeight(45);
    //deviceMock.setId(4568);
    deviceMock.setName("Android");
    deviceMock.setOwner(1111);
    deviceMock.setPlatform("Windows NT");
    deviceMock.setUuid("522601");
    deviceMock.setVersion("1.0");
    deviceMock.setWidth(76);
    mockRegObj.setEmail("bbb@gmail.com");
    /*mockRegObj.setId(399);*/
    mockRegObj.setName("bbb");
    mockRegObj.setPassword("BBB");
    mockRegObj.setDevice(deviceMock);
    loginServiceObj.newAccount(mockRegObj);

    //assertEquals("New Account Creation", "", "");
}

任何需要在测试类中修改的东西,请告诉我..

4

2 回答 2

2

在您的测试中LoginServiceImpl loginServiceObj = new LoginServiceImpl(); ,弹簧没有实例化,因此不会应用任何注释。您需要自动装配它,或以其他方式注入它。Spring 3.2 让这种东西超级简单易用。

我的其余答案仍然很好:您尚未在 java 代码中声明或实例化 jdbctemplate。而且您还没有在 xml 文件中定义它。

你需要这个

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref bean="dateSource"/>
        </property>
    </bean>

然后 this 作为实例变量(假设您使用注释)

   @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;
于 2013-02-13T11:51:37.367 回答
1

正如@NimChimpsky 提到的,你需要jdbcTemplate在你的bean xml 文件中定义你的,然后在你的实例变量中你也可以这样做。

@Autowired
private JdbcTemplate jdbcTemplate;
于 2013-02-13T11:58:32.763 回答