我正在尝试为添加到CrudRepository接口的自定义方法编写单元测试。面临的问题是所有Crud defualt方法都在执行,而我的自定义方法始终返回空数据集。例如findOne(id),findAll可以正常工作,没有任何问题。目前正在努力寻找答案。
数据库表帐户的实体类
@Entity(name = "account")
public class Account implements Serializable {
/**
* UUID
*/
private static final long serialVersionUID = 3918263534182744304L;
/**
* Primary Key account Id {@link Long}
*/
@Id
@Column(name = "accountId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long accountId;
/**
* Actual accountID received from Sales-force
*/
@Size(max = 18)
@Column(name = "id")
private String id;
/**
* Name of the account
*/
@Size(max = 255)
@Column(name = "Name")
private String name;
/**
* Type of the account
*/
@Size(max = 255)
@Column(name = "type")
private String type;
//other fields and getter and setters
}
存储库界面
@Repository
@Transactional(propagation=Propagation.REQUIRES_NEW)
public interface AccountRepository extends CrudRepository<Account, Long>{
Collection<Account> findByType(final String type);
}
春季单元测试课
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
@Transactional
public class AccountRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private AccountRepository accountRepository;
private Long accountId_1 = 1L;
private Long accountId_2 = 2L;
@Before
public void init() {
//account 1
Account account = setAccount("Credit");
entityManager.persist(account);
entityManager.flush();
logger.info("Account Id Inserted: " + account.getAccountId() + " | " + account.toString());
accountId_1 = account.getAccountId();
//account 2
account = setAccount("Debit");
entityManager.persist(account);
entityManager.flush();
logger.info("Account Id Inserted: " + account.getAccountId() + " | " + account.toString());
accountId_2 = account.getAccountId();
}
@Test
public void accountTypeTest() {
Account retrieved = accountRepository.findOne(accountId_2);
//correctly returning the object with accountId == accountId_2
Collection<Account> accountRetrived = accountRepository.findByType(retrieved.getType());
// Always returning empty result set
assertTrue(accountRetrieved.size() > 0);
}
/*
* Method will create the Account dummy object.
*/
private Account setAccount(final String type) {
final Account account = new Account();
account.setiD("ID");
account.setName("AccountName");
account.setType(type);
return account;
}
}