如何使用 mockito 为以下代码编写 junit 测试?
Posted
技术标签:
【中文标题】如何使用 mockito 为以下代码编写 junit 测试?【英文标题】:How to write junit test for below code using mockito? 【发布时间】:2019-05-24 07:44:21 【问题描述】:您好,我是使用 mockito 进行 groovy 单元测试的新手。我想弄清楚如何在不真正更新或插入数据库的情况下为 daoImpl calss 编写测试用例。
下面是我的代码。
@Component
public class TransactionDAOImpl implements TransactionDAO
@Autowired
StringUtilities stringUtilities;
@Autowired
private TransactionRepository transactionRespository;
@Override
@Transactional
public String create(List<DepositoryTransaction> depositoryTransaction)
List<DepositoryTransaction> dep = transactionRespository.saveAll(depositoryTransaction);
LOGGER.debug("Recieved atm transaction : = ", dep);
if (dep != null && !dep.isEmpty())
return stringUtilities.SUCCESS;
else
return stringUtilities.FAILURE;
【问题讨论】:
好像是重复的***.com/q/37911776/1091731 【参考方案1】:@RunWith(MockitoJUnitRunner.class) // org.mockito.runners.MockitoJUnitRunner is deprecated so use org.mockito.junit.MockitoJUnitRunner instead
public class TransactionDAOImplTest
@InjectMocks
private TransactionDAOImpl transactionDAOImpl;
@Mock
StringUtilities stringUtilities;
@Mock
private TransactionRepository transactionRespository;
List<DepositoryTransaction> depositoryTransaction=new ArrayList<>();
@Test
public void testCreateSaveAllNullReturn()
when(transactionRespository.saveAll(depositoryTransaction)).thenReturn(null);
assertThat(transactionDAOImpl.create(depositoryTransaction)).isEqualTo(stringUtilities.SUCCESS); // i do not khnow if this is an enum ?
@Test
public void testCreateSaveAllEmptyReturn()
when(transactionRespository.saveAll(depositoryTransaction)).thenReturn(new ArrayList<>());
assertThat(transactionDAOImpl.create(depositoryTransaction)).isEqualTo(stringUtilities.SUCCESS); // i do not khnow if this is an enum ?
@Test
public void testCreateSaveAllNotEmptyAndNotNullReturn()
DepositoryTransaction obj=new DepositoryTransaction();
depositoryTransaction.add(obj);
when(transactionRespository.saveAll(depositoryTransaction)).thenReturn(depositoryTransaction);
assertThat(transactionDAOImpl.create(depositoryTransaction)).isEqualTo(stringUtilities.FAILURE); // i do not khnow if this is an enum ?
【讨论】:
以上是关于如何使用 mockito 为以下代码编写 junit 测试?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用mockito和junit为Java中的ExecutorService编写测试用例?
如何使用junit和mockito为私有void方法编写测试用例[重复]