我已经从 Mockito for Spring
一书中找到了以下测试import com.packt.trading.dto.Stock;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class StockBrokerTest {
@Mock MarketWatcher marketWatcher;
@Mock Portfolio portfolio;
StockBroker broker;
@Before public void setUp() {
broker = new StockBroker(marketWatcher);
}
@Test
public void when_ten_percent_gain_then_the_stock_is_sold() {
//Portfolio's getAvgPrice is stubbed to return $10.00
when(portfolio.getAvgPrice(isA(Stock.class))).thenReturn(new BigDecimal("10.00"));
verify(portfolio.getAvgPrice(isA(Stock.class)))
//A stock object is created with current price $11.20
Stock aCorp = new Stock("A", "A Corp", new BigDecimal("11.20"));
//getQuote method is stubbed to return the stock
when(marketWatcher.getQuote(anyString())).thenReturn(aCorp);
//perform method is called, as the stock price increases by 12% the broker should sell the stocks
broker.perform(portfolio, aCorp);
//verifying that the broker sold the stocks
verify(portfolio).sell(aCorp,10);
}
public void perform(Portfolio portfolio,Stock stock) {
Stock liveStock = market.getQuote(stock.getSymbol());
BigDecimal avgPrice = portfolio.getAvgPrice(stock);
BigDecimal priceGained =
liveStock.getPrice().subtract(avgPrice);
BigDecimal percentGain = priceGained.divide(avgPrice);
if(percentGain.compareTo(LIMIT) > 0) {
portfolio.sell(stock, 10);
}else if(percentGain.compareTo(LIMIT) < 0){
portfolio.buy(stock);
}
}
我致电
when(portfolio.getAvgPrice(isA(Stock.class))).thenReturn(new BigDecimal("10.00"));
但未验证是否使用了调用getAvgPrice()的验证语句。 此外,我在测试用例中没有进一步使用返回值。
我们是否只应该对那些在测试用例中评估或进一步使用其返回值的方法进行存根? 我们不能写一个没有verify()或返回值断言的when()吗?虽然,在这两种情况下我的测试都成功运行。
使用Mockito是错误的吗?
答案 0 :(得分:1)
每当您对方法进行单元测试时,请记住:
您正在将该方法作为UNIT进行测试。当您向UNIT(方法)提供所有必需的数据时,您必须
verify
/assert
州,结果是否符合您的期望。
exception
场景。当您传递错误数据时,预期结果将是例外。您正在测试异常状态。测试用例会成功,因为它在执行时没有遇到任何异常行为。一般来说,verify
或assert
州是使单元测试有意义的原因