简体   繁体   中英

Spring unit test not getting the updated values from database

I have simple spring configuration using plain spring jdbc with dao in place. I have added a test case for the dao layer which does the following functionality. - Get the settings - test the number of records and the values - Update the settings with new values - test the updated values.

I am not able to assert the values with the updated, below is the error I am getting. Not sure what is wrong.

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.386 sec <<< FAILURE!
updateTest(com.sims.service.SettingsServiceTests)  Time elapsed: 1.086 sec  <<< FAILURE!
org.junit.ComparisonFailure: expected:<[My Org]> but was:<[New Org1]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.abc.service.SettingsServiceTests.updateTest(SettingsServiceTests.java:57)

Can any one let me know what is wrong in the configuration. I have added applicationContext.xml, Dao and unit test for dao.

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<!-- import the dataSource definition -->
<import resource="datasource-config.xml" />

<context:component-scan base-package="com.abc" />

<tx:annotation-driven transaction-manager="transactionManager" />

<context:property-placeholder location="classpath:spring/data-access.properties"
    system-properties-mode="OVERRIDE" />

<tx:annotation-driven />


<!-- Transaction manager for a single JDBC DataSource (alternative to JTA) -->
<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    p:dataSource-ref="dataSource" />

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="dataSource" />
</bean>

<bean id="namedParameterJdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource" />

SettingsDaoImpl.java

@Repository
public class SettingsDaoImpl extends BaseDao{

private static final class SettingMapper implements RowMapper<Settings> {

    public SettingMapper() {
        super();
    }

    @Override
    public Settings mapRow(final ResultSet rs, final int rowNum) throws SQLException {
        final Settings settings= new Settings();

        settings.setId(rs.getLong("id"));
        settings.setOrgName(rs.getString("org_name"));
        settings.setOrgAddress(rs.getString("org_address"));
        settings.setOrgPhone(rs.getString("org_phone"));
        settings.setLanguage(rs.getString("language"));
        settings.setTimeZone(rs.getString("time_zone"));
        settings.setCountry(rs.getString("country"));
        settings.setCurrencyType(rs.getString("currency"));

        return settings;
    }
}

@Transactional(readOnly = true)
public Settings getSettings(){
    final String sql = "select * from settings";
    final Settings student = new Settings();

    final SqlParameterSource paramSource = new BeanPropertySqlParameterSource(
            student);

    final List<Settings> result = this.getNamedParameterJdbcTemplate().query(
            sql, paramSource, new SettingMapper());

    if (result != null && !result.isEmpty()) {
        return result.get(0);
    }
    return null;
}

@Transactional(readOnly = false)
public Settings saveSetting(Settings settings) {
    Settings tSettings = null;
    if (settings.isNew()) {
        tSettings = insert(settings);
    } else {
        tSettings = update(settings);
    }

    return tSettings;
}


public Settings insert(Settings settings){
    final String sql = "insert into settings (org_name, org_address, org_phone, language, time_zone, country, currency) "
    +" values (:orgName, :orgAddress, :orgPhone, :language, :timeZone, :country, :currency)";
    final GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    final String[] keyColumnNames = { "id" };

    final SqlParameterSource paramSource = new BeanPropertySqlParameterSource(
            settings);

    final int count = this.getNamedParameterJdbcTemplate().update(sql,
            paramSource, generatedKeyHolder, keyColumnNames);

    settings.setId(generatedKeyHolder.getKey().longValue());
    return settings;
}

public Settings update(final Settings settings) throws DataAccessException {
        final StringBuilder updateClause = new StringBuilder();
        SettingDb.getUpdateSql(updateClause);
        final String sql = "update settings set org_name:=orgName, org_address:= orgAddress, " +
        org_phone:=orgPhone, language:=language, time_zone:=timeZone, country:=country, currency:=currency where id=:id";

        final GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        final String[] keyColumnNames = { "id" };

        final SqlParameterSource paramSource = new BeanPropertySqlParameterSource(
                settings);

        final int count = this.getNamedParameterJdbcTemplate().update(sql,
                paramSource, generatedKeyHolder, keyColumnNames);

        return settings;
}

}

SettingsDAOTests.java

@Transactional(propagation = Propagation.NESTED)
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class SettingsDAOTests {

@Autowired
private SettingsDaoImpl settingsDaoImpl;

@Test
public void testSettings(){

    Settings settings = settingsDaoImpl.getSettings();
    Assert.assertNotNull(settings);

    String orgName = "New Org";
    String orgAddress = "New Org Ad";
    String phoneNumber = "Ph1";
    String language = "Hindi";
    String timeZone = "GMT";
    String country = "US";
    String currency = "Dollar";

    settings.setCountry(country);
    settings.setOrgAddress(orgAddress);
    settings.setOrgName(orgName);
    settings.setOrgPhone(phoneNumber);
    settings.setLanguage(language);
    settings.setTimeZone(timeZone);
    settings.setCurrencyType(currency);

    settingsDaoImpl.saveSetting(settings);

    Settings settings1 = settingsDaoImpl.getSettings();

    Assert.assertEquals(orgName, settings1.getOrgName());
    Assert.assertEquals(orgAddress, settings1.getOrgAddress());
    Assert.assertEquals(phoneNumber, settings1.getOrgPhone());
    Assert.assertEquals(timeZone, settings1.getTimeZone());
    Assert.assertEquals(country, settings1.getCountry());
    Assert.assertEquals(currency, settings1.getCurrencyType());

    String orgName1 = "New Org1";
    String orgAddress1 = "New Org Ad1";
    String phoneNumber1 = "Ph11";
    String language1 = "Hindi1";
    String timeZone1 = "GMT1";
    String country1 = "US1";
    String currency1 = "Dollar1";

    settings.setCountry(country1);
    settings.setOrgAddress(orgAddress1);
    settings.setOrgName(orgName1);
    settings.setOrgPhone(phoneNumber1);
    settings.setLanguage(language1);
    settings.setTimeZone(timeZone1);
    settings.setCurrencyType(currency1);

    settingsDaoImpl.saveSetting(settings);

    Settings settings2 = settingsDaoImpl.getSettings();

    Assert.assertEquals(orgName, settings2.getOrgName());
    Assert.assertEquals(orgAddress, settings2.getOrgAddress());
    Assert.assertEquals(phoneNumber, settings2.getOrgPhone());
    Assert.assertEquals(timeZone, settings2.getTimeZone());
    Assert.assertEquals(country, settings2.getCountry());
    Assert.assertEquals(currency, settings2.getCurrencyType());
}
}

Spring将在您使用时回滚数据库更新:

defaultRollback=true

I am answering as I cannot comment. I would suggest you to refer the following link:- http://www.journaldev.com/2603/spring-transaction-management-example-with-jdbc

what I feel you are getting some sort of exception, put a try catch block while calling database query. try looking deep into stack trace you will find your solution.

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