Does mockito have an equivalent idiom to jMock's States?

后端 未结 2 2059
说谎
说谎 2021-01-04 07:47

The book Growing Object Oriented Software gives several examples in jMock where the state is made explicit without exposing it through an API. I really like this id

2条回答
  •  礼貌的吻别
    2021-01-04 08:09

    I used a spy for the self same exercise:

    http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#13

    I changed my SniperListener mock into a spy thus:

    private final SniperListener sniperListenerSpy = spy(new SniperListenerStub());
    private final AuctionSniper sniper = new AuctionSniper(auction, sniperListenerSpy);
    

    And also created a stubbed implementation of SniperListener:

    private class SniperListenerStub implements SniperListener {
        @Override
        public void sniperLost() {
        }
    
        @Override
        public void sniperBidding() {
            sniperState = SniperState.bidding;
        }
    
        @Override
        public void sniperWinning() {
        }
    }
    

    The book uses JMock's "States", but I used a nested enum instead:

    private SniperState sniperState = SniperState.idle;
    
    private enum SniperState {
        idle, winning, bidding
    }
    

    You then have to use regular JUnit asserts to test for the state:

    @Test
    public void reportsLostIfAuctionClosesWhenBidding() {
        sniper.currentPrice(123, 45, PriceSource.FromOtherBidder);
        sniper.auctionClosed();
        verify(sniperListenerSpy, atLeastOnce()).sniperLost();
        assertEquals(SniperState.bidding, sniperState);
    }
    

提交回复
热议问题