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


accountService.transfer( "1", "2", 50 );
Assertions.assertEquals( 150, senderAccount.getBalance() );
Assertions.assertEquals( 150, beneficiaryAccount.getBalance() );
}
@AfterEach
public void tearDown()
{
verify( mockAccountManager );
}
}
4. JMock技术JMock依赖下面11个jar包 。 另外JMock不完全兼容JUnit5
轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)TestAccountServiceJMock.java
package com.account;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.Expectations;
import org.jmock.Mockery;
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.junit.runner.RunWith;
import com.account.Account;
import com.account.AccountManager;
import com.account.AccountService;
@RunWith(JMock.class)
public class TestAccountServiceJMock {
/**
* The mockery context that we use to create our mocks.
*/
private Mockery context = new JUnit4Mockery();
/**
* The mock instance of the AccountManager to use.
*/
private AccountManager mockAccountManager;
@BeforeEach
public void setUp(){
mockAccountManager = context.mock( AccountManager.class );
}
@Test
@DisplayName("测试转账")
public void testTransferOk()
{
final Account senderAccount = new Account( "1", 200 );
final Account beneficiaryAccount = new Account( "2", 100 );
context.checking( new Expectations()
{
{
oneOf( mockAccountManager ).findAccountForUser( "1" );
will( returnValue( senderAccount ) );
oneOf( mockAccountManager ).findAccountForUser( "2" );
will( returnValue( beneficiaryAccount ) );
oneOf( mockAccountManager ).updateAccount( senderAccount );
oneOf( mockAccountManager ).updateAccount( beneficiaryAccount );
}
} );
AccountService accountService = new AccountService();
accountService.setAccountManager( mockAccountManager );
accountService.transfer( "1", "2", 50 );
Assertions.assertEquals( 150, senderAccount.getBalance() );
Assertions.assertEquals( 150, beneficiaryAccount.getBalance() );
}
}
4.1 One , one of
JMock2.4版以前:one;
JMock2.51版以后:one of 。
oneOf (anObject).doSomething(); will(returnValue(10));
oneOf (anObject).doSomething(); will(returnValue(20));
oneOf (anObject).doSomething(); will(returnValue(30));
第一次调用时会返回10 , 第二次会返回20 , 第三次会返回30 。
4.2 atLeast(n).of
atLeast(1).of (anObject).doSomething();
will(onConsecutiveCalls( returnValue(10), returnValue(20), returnValue(30)));
这里atLeast (1)表明doSomething方法将至少被调用一次 , 但不超过3次 。 且调用的返回值分别是10、20、30.
轻拔琴弦|测试工程师成神之路丨Java单元测试——Mock技术(代码)5. mockito技术需要mockito-all-1.9.5.jar包 。