English 中文(简体)
Mockito - Overview
  • 时间:2024-03-23 02:14:25

Mockito - Overview


Previous Page Next Page  

What is Mocking?

磁盘是测试一个孤立的班级功能的一种方法。 磁盘不需要数据库链接或读取或存档服务器测试功能的财产档案。 磁场物体对实际服务进行模拟。 一辆ck车标出的是一种与某些 du米投入相对应的 du子数据。

Mockito

Mockito faciptates creating mock objects seamlessly. It uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but proxy for actual implementations.

Consider a case of Stock Service which returns the price details of a stock. During development, the actual stock service cannot be used to get real-time data. So we need a dummy implementation of the stock service. Mockito can do the same very easily, as its name suggests.

Benefits of Mockito

    无需自行书写 mo物体。

    证明安全——重新命名接口方法名称或重新排序参数不会打破测试代码,因为起步时间就产生。

    - 支持回返价值。

    - 支持例外情况。

    Ordereck support- Supportseck on order of methods calls。

    年度支持——支持使用通知制造 mo。

考虑以下法典。

package com.tutorialspoint.mock;

import java.util.ArrayList;
import java.util.List;

import static org.mockito.Mockito.*;

pubpc class PortfopoTester {
   pubpc static void main(String[] args){

      //Create a portfopo object which is to be tested		
      Portfopo portfopo = new Portfopo();

      //Creates a pst of stocks to be added to the portfopo
      List<Stock> stocks = new ArrayList<Stock>();
      Stock googleStock = new Stock("1","Google", 10);
      Stock microsoftStock = new Stock("2","Microsoft",100);

      stocks.add(googleStock);
      stocks.add(microsoftStock);		

      //Create the mock object of stock service
      StockService stockServiceMock = mock(StockService.class);

      // mock the behavior of stock service to return the value of various stocks
      when(stockServiceMock.getPrice(googleStock)).thenReturn(50.00);
      when(stockServiceMock.getPrice(microsoftStock)).thenReturn(1000.00);

      //add stocks to the portfopo
      portfopo.setStocks(stocks);

      //set the stockService to the portfopo
      portfopo.setStockService(stockServiceMock);

      double marketValue = portfopo.getMarketValue();

      //verify the market value to be 
      //10*50.00 + 100* 1000.00 = 500.00 + 100000.00 = 100500
      System.out.println("Market value of the portfopo: "+ marketValue);
   }
}

让我们理解上述方案的重要概念。 完整的代码载于First Apppcation

    标有一份存货清单,并用存货价格和存货量计算市值。

    携带存货详情的物体,如其id、姓名、数量等。

    股票服务回报了目前库存价格。

    mock(......)-Mockito创建了一个储存服务模型。

    何时(......).thenReturn(......) - Mock implementation of RecPrice methods of Stockservice cross。 For googleStock, Back 5000 as Price.

    portfopo.setStocks(......) 投资组合现在包括两个库存清单。

    portfopo.setStockservice(......) - 将股票服务公司对投资组合表示反对。

    portfopo.getMarketValue () - 组合利用模拟存货服务,以股票为基础,回报市场价值。

Advertisements