轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)( 二 )


private HashMap accounts = new HashMap();
public void addAcount(String userId,Account account){
this.accounts.put(userId,account);
}
public Account findAccountForUser(String userId){
return this.accounts.get(userId);
}
public void updateAccount(Account account){
//do nothing
}
}
Account.java
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class TestAccountService {
@Test
public void testTransferOK() {
StubAccountManager stubAccountManager = new StubAccountManager(); //定义MockAccountManager类
Account sendAccount = new Account("1",200); //定义收钱方和出钱方两个Account
Account beneficiaryAccount = new Account("2",100);
stubAccountManager.addAcount("1", sendAccount); //初始化收钱方和出钱方HashMap
stubAccountManager.addAcount("2", beneficiaryAccount);
AccountService accountService = new AccountService(); //初始化AccountService类
accountService.setAccountManager(stubAccountManager); //初始化AccountManager
accountService.transfer("1","2",50); //转钱
Assertions.assertEquals(150,sendAccount.getBalance()); //判断转换后收付方金额是否正确
Assertions.assertEquals(150,beneficiaryAccount.getBalance());
}}
3.EasyMock技术EasyMock需要以下两个jar包:easymock-2.4.jar和easymockclassextension-2.4.jar
TestAccountServiceEasyMock.java
package com.account;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.verify;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.account.Account;
import com.account.AccountManager;
import com.account.AccountService;
public class TestAccountServiceEasyMock {
private AccountManager mockAccountManager;
@BeforeEach
public void setUp()
{
//初始化easyMock
mockAccountManager = createMock("mockAccountManager", AccountManager.class );
}
@Test
@DisplayName("测试转账")
public void testTransferOk()
{
Account senderAccount = new Account( "1", 200 );
Account beneficiaryAccount = new Account( "2", 100 );
//开始定义期望
mockAccountManager.updateAccount( senderAccount );
mockAccountManager.updateAccount( beneficiaryAccount );
//EasyMock的expect和replay方法
expect( mockAccountManager.findAccountForUser( "1" ) ).andReturn( senderAccount ); //期望返回senderAccount
expect( mockAccountManager.findAccountForUser( "2" ) ).andReturn( beneficiaryAccount ); //期望返beneficiaryAccount
replay( mockAccountManager );//切换到replay状态 Record-> replay , 在replay状态才可以进行验证
AccountService accountService = new AccountService();
accountService.setAccountManager( mockAccountManager );


推荐阅读