一個簡單的使用mock技術進行測試的例子

Account:java

public class Account {
    private String acountId;
    private long balance;

    public Account(String acountId, long balance) {
        this.acountId = acountId;
        this.balance = balance;
    }

    public void debit(long amount) {
        this.balance-=amount;
    }

    public void credit(long amount) {
        this.balance+=amount;
    }

    public long getBalance() {
        return balance;
    }
}

 

AccountManager:this

public interface AccountManager {
    Account findAccountForUser(String userId);

    void updateAccount(Account account);
}

 

AccountService:spa

public class AccountService {
    private AccountManager accountManager;

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public void transfer(String senderId, String befeficiaryId, long amount) {
        Account sender = this.accountManager.findAccountForUser(senderId);
        Account beneficiary = this.accountManager.findAccountForUser(befeficiaryId);

        sender.debit(amount);
        beneficiary.credit(amount);

        this.accountManager.updateAccount(sender);
        this.accountManager.updateAccount(beneficiary);
    }
}

 

TestAccountService:code

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class TestAccountService {
    public class MockAccountManager implements AccountManager {
        private Map<String,Account> accounts = new HashMap<String,Account>();

        public void addAccount(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...
        }
    }

    @Test
    public void testTransferOk(){
        MockAccountManager mockAccountManager = new MockAccountManager();

        Account senderAccount = new Account("1", 200);
        Account deneficiaryAccount = new Account("1", 100);
        mockAccountManager.addAccount("1", senderAccount);
        mockAccountManager.addAccount("2", deneficiaryAccount);
        AccountService accountService = new AccountService();
        accountService.setAccountManager(mockAccountManager);
        accountService.transfer("1","2",50);

        assertEquals(150,senderAccount.getBalance());
        assertEquals(150,deneficiaryAccount.getBalance());
    }
}
相關文章
相關標籤/搜索