Does Java – mockito have the same idiom as jmock’s country?
•
Java
The book "object oriented software" provides several examples in jmock, in which the state is explicit and will not be exposed through the API I really like the idea Is there any way to do this in mockito?
This is an example of this book
public class SniperLauncherTest { private final States auctionState = context.states("auction state") .startsAs("not joined"); @Test public void addsNewSniperToCollectorAndThenJoinsAuction() { final String itemId = "item 123"; context.checking(new Expectations() {{ allowing(auctionHouse).auctionFor(itemId); will(returnValue(auction)); oneOf(sniperCollector).addSniper(with(sniperForItem(item))); when(auctionState.is("not joined")); oneOf(auction).addAuctionEventListener(with(sniperForItem(itemId))); when(auctionState.is("not joined")); one(auction).join(); then(auctionState.is("joined")); }}); launcher.joinAuction(itemId); } }
Solution
I do the same exercise with Spies:
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#13
I turned my sniperlistener simulator into a spy:
private final SniperListener sniperListenerSpy = spy(new SniperListenerStub()); private final AuctionSniper sniper = new AuctionSniper(auction,sniperListenerSpy);
A stub implementation of sniperlistener is also created:
private class SniperListenerStub implements SniperListener { @Override public void sniperLost() { } @Override public void sniperBidding() { sniperState = SniperState.bidding; } @Override public void sniperWinning() { } }
This book uses jmock's "states", but I use a nested enumeration:
private SniperState sniperState = SniperState.idle; private enum SniperState { idle,winning,bidding }
You must then test the state using regular JUnit assertions:
@Test public void reportsLostIfAuctionClosesWhenBidding() { sniper.currentPrice(123,45,PriceSource.FromOtherBidder); sniper.auctionClosed(); verify(sniperListenerSpy,atLeastOnce()).sniperLost(); assertEquals(SniperState.bidding,sniperState); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码