package demo;

import cn.quantgroup.xyqb.config.data.JpaConfig;
import cn.quantgroup.xyqb.config.data.RedisConfig;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.repository.IUserRepository;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;

/**
 * 持久层测试用例
 * @author renwc
 * @date 2018-01-05
 */
@Rollback
@Transactional(rollbackFor = Exception.class)
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = {JpaConfig.class, RedisConfig.class}, initializers = ApolloPropertySourceInitializer.class)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class RepsitoryJpaTest {

    @Resource
    private TestEntityManager entityManager;
    @Resource
    private IUserRepository userRepository;

    @Test(expected = PersistenceException.class)
    public void testSaveExample() throws Exception {
        String phone = "13461067662";
        User user = new User();
        user = userRepository.save(user);
        User userRep = userRepository.findByPhoneNo(phone);
        Assert.assertEquals(user, userRep);
    }

    @Test
    public void testExample() throws Exception {
        String phone = "13461067662";
        String password = "318e235d3e52648b236faa3f748000d5";//123456
        User user = new User();
        user.setPhoneNo(phone);
        user.setPassword(password);
        user.setCreatedAt(Timestamp.from(Instant.now()));
        user.setUpdatedAt(user.getCreatedAt());
        user = userRepository.save(user);
        User userRep = userRepository.findByPhoneNo(phone);
        Assert.assertEquals(user, userRep);
    }

}
