本文主要是介绍junit mockito Dao层,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Dao层单元测试需要启动服务的上下文
业务逻辑需要别名进行MOCK打桩
为了不影响测试结果和对数据库产生脏数据,使用@Sql注解来完成相关数据的初始化和清除
Dao
public interface BranchDao extends BaseDao<BranchPO, Long> {@Modifying@Transactional@Query(nativeQuery = true,value = "update T_BRANCH_INFO set ADDRESS=?2, UPDATE_DATE=sysdate where BRANCH_NO=?1")int updateAddressByBranchNo(Long branchNo, String address);}
Service Impl
@Slf4j
@Service
public class BranchServiceImpl implements BranchService {@Autowiredprivate BranchRepository branchRepository;@Overridepublic boolean updateAddressByBranchNo(Long branchNo, String address) {if (branchNo == null || address == null) {return false;}try {return branchRepository.updateAddressByBranchNo(branchNo, address) > 0;} catch (Exception e) {log.error("修改营业部的地址异常, branchNo={}, address={}", branchNo, address, e);}return false;}
}
BaseTest
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class BaseTest extends Mockito {
}
Test
@Slf4j
public class BranchServiceImplTest extends BaseTest {@Autowired//Autowired为了上下文测试private BranchServiceImpl branchService;@InjectMocks//InjectMocks启个别名Mock打桩单元测试private BranchServiceImpl mockBranchService;@Mockprivate BranchRepository branchRepository;@Beforepublic void init() {MockitoAnnotations.initMocks(this);}@Testpublic void updateAddressByBranchNo_NullBranchNo_ReturnsFalse() {boolean result = branchService.updateAddressByBranchNo(null, "123 Main St");Assert.assertFalse(result);}@Testpublic void updateAddressByBranchNo_NullAddress_ReturnsFalse() {boolean result = branchService.updateAddressByBranchNo(1L, null);Assert.assertFalse(result);}@Test@SqlGroup({@Sql(statements = {"insert into t_branch_info(id,branch_no,branch_name,address) values(seq_branch_info.nextval,100,'营业部名称','营业部地址')"},executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD),@Sql(statements = {"delete t_branch_info where branch_no=100"},executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)})public void updateAddressByBranchNo_Success_ReturnsTrue() {BranchInfoVO vo = branchService.findByBranchNo(100L);Assert.assertEquals("营业部名称",vo.getBranchName());Assert.assertEquals("营业部地址",vo.getAddress());boolean result = branchService.updateAddressByBranchNo(100L, "123 Main St");Assert.assertTrue(result);vo = branchService.findByBranchNo(100L);Assert.assertEquals("123 Main St",vo.getAddress());}@Testpublic void updateAddressByBranchNo_Update_ReturnsFalse() {boolean result = branchService.updateAddressByBranchNo(100L, "123 Main St");Assert.assertFalse(result);}@Testpublic void updateAddressByBranchNo_Exception_ReturnsFalse() {when(branchRepository.updateAddressByBranchNo(anyLong(),anyString())).thenThrow(new RuntimeException());boolean result = mockBranchService.updateAddressByBranchNo(100L, "123 Main St");Assert.assertFalse(result);}
}
这篇关于junit mockito Dao层的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!