私はMockitoにかなり慣れていないので、クリーンアップに問題があります。
以前は単体テストに JMock2 を使用していました。私の知る限り、JMock2 は、テスト メソッドごとに再構築されるコンテキストで期待値やその他のモック情報を保持します。したがって、すべてのテスト方法が他の方法に干渉されることはありません。
私は JMock2 を使用するときにスプリング テストに同じ戦略を採用しました。投稿で使用した戦略に潜在的な問題があることがわかりました。アプリケーション コンテキストはテスト メソッドごとに再構築されるため、テスト手順全体が遅くなります。
多くの記事が春のテストで Mockito を使用することを推奨していることに気付きました。試してみたいと思います。テストケースに2つのテストメソッドを書くまではうまくいきます。各テスト メソッドは、単独で実行すると合格し、一緒に実行するとそのうちの 1 つが失敗しました。これは、モック情報がモック自体に保存されており (JMock にそのようなコンテキスト オブジェクトが表示されないため)、モック (およびアプリケーション コンテキスト) が両方のテスト メソッドで共有されているためだと推測しました。
@Before メソッドに reset() を追加して解決しました。私の質問は、この状況を処理するためのベストプラクティスは何ですか? どんなアイデアでも大歓迎です、事前に感謝します。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/booking-servlet.xml",
"classpath:test-booking-servlet.xml" })
@WebAppConfiguration
public class PlaceOrderControllerIntegrationTests implements IntegrationTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Autowired
private PlaceOrderService placeOrderService;
@Before
public void setup() {
this.mockMvc = webAppContextSetup(this.wac).build();
reset(placeOrderService);// reset mock
}
@Test
public void fowardsToFoodSelectionViewAfterPendingOrderIsPlaced()
throws Exception {
final Address deliveryAddress = new AddressFixture().build();
final String deliveryTime = twoHoursLater();
final PendingOrder pendingOrder = new PendingOrderFixture()
.with(deliveryAddress).at(with(deliveryTime)).build();
when(placeOrderService.placeOrder(deliveryAddress, with(deliveryTime)))
.thenReturn(pendingOrder);
mockMvc.perform(...);
}
@Test
public void returnsToPlaceOrderViewWhenFailsToPlaceOrder() throws Exception {
final Address deliveryAddress = new AddressFixture().build();
final String deliveryTime = twoHoursLater();
final PendingOrder pendingOrder = new PendingOrderFixture()
.with(deliveryAddress).at(with(deliveryTime)).build();
NoAvailableRestaurantException noAvailableRestaurantException = new NoAvailableRestaurantException(
deliveryAddress, with(deliveryTime));
when(placeOrderService.placeOrder(deliveryAddress, with(deliveryTime)))
.thenThrow(noAvailableRestaurantException);
mockMvc.perform(...);
}