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


package com.account;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import com.account.Account;
import com.account.AccountManager;
import com.account.AccountService;
public class TestAccountServiceMockito {
private AccountManager mockAccountManager;
private Account senderAccount;
private Account beneficiaryAccount;
@BeforeEach
public void setUp(){
mockAccountManager = Mockito.mock(AccountManager.class);
senderAccount = new Account( "1", 200 );
beneficiaryAccount = new Account( "2", 100 );
mockAccountManager.updateAccount( senderAccount );
mockAccountManager.updateAccount( beneficiaryAccount );
when(mockAccountManager.findAccountForUser("1")).thenReturn( senderAccount );
when(mockAccountManager.findAccountForUser("2")).thenReturn( beneficiaryAccount );
}
@Test
@DisplayName("测试转账")
public void test() {
AccountService accountService = new AccountService();
accountService.setAccountManager( mockAccountManager );
accountService.transfer( "1", "2", 50 );
Assertions.assertEquals( 150, senderAccount.getBalance() );
Assertions.assertEquals( 150, beneficiaryAccount.getBalance() );
}
}
【轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)】#学习视频#※※【重要通知】本期超级福利:《1个案例快速上手web自动化测试》课程 , 今日限时0元!(限时免费听)参与方式:私信“免费听”即可获取完整视频 。


推荐阅读