Hi Steve,
Based on your advice, the simplest solution seems to be moving the constructor into each test method, after the Expectations block:
1: @RunWith(JMock.class)
2: public class AuctionSniperTest {
3: ...
4: private final SniperListener sniperListener = context.mock(SniperListener.class);
5: // no constructor here
6:
7: @Test public void
8: reportsJoiningWhenConstructed() {
9: context.checking(new Expectations() {{
10: one(sniperListener).sniperJoining();
11: }});
12: new AuctionSniper(sniperListener); // constructor here
13: }
14:
15: @Test public void
16: reportsLostIfAuctionClosesImmediately() {
17: context.checking(new Expectations() {{
18: allowing(sniperListener).sniperJoining();
19: one(sniperListener).sniperLost();
20: }});
21: AuctionSniper sniper = new AuctionSniper(sniperListener); // constructor here
22: sniper.auctionClosed();
23: }
24: ...
25: }
After doing so, the tests are running as expected.
And I also found that this seems similar to the NUnit style, where the same instance of the test class is reused for all the test methods, so the constructor cannot be put at the class field, either.
Anyway, thank you very much for your helpful advice!
Regards,
Chengwei
Steve Freeman 在 2022年2月22日 星期二下午5:17:46 [UTC+8] 的信中寫道: