iT邦幫忙

2024 iThome 鐵人賽

DAY 14
0

在Day12 - Controller下的Bean (下) 時,我們實作了一支 API 用於取得 A、B兩個參數的最大公因數,但當時只介紹了 Controller 類別的流程。今天,就來繼續探討該範例中的業務邏輯。

實作範例

@Service("ExampleService")
public class ExampleService {

		/**
     * 計算兩數的最大公因數
     */
    public int getHighestCommonFactor(int paramA, int paramB) {
        logger.info("paramA = " + paramA + ", B = " + paramB);
        while (paramB != 0) {
            int tmp = paramA % paramB;
            paramA = paramB;
            paramB = tmp;
        }
        return paramA;
    }
    
}

在這個範例中,ExampleService 這個類帶有 @Service 註解,就代表它是負責處理程式核心的業務邏輯。

目前在這個類別中只有一個方法,即 getHighestCommonFactor() 用用於計算兩個參數的最大公因數。假設今天有個需求是需要一個計算兩數最小公倍數的 API,那麼我們就可以在此類別下擴充新的方法,讓該 API 呼叫該方法進行對應的數學運算。

新增方法後的類別如下:

@Service("ExampleService")
public class ExampleService {

    /**
     * 計算兩數的最大公因數
     */
    public int getHighestCommonFactor(int paramA, int paramB) {
        logger.info("paramA = " + paramA + ", B = " + paramB);
        while (paramB != 0) {
            int tmp = paramA % paramB;
            paramA = paramB;
            paramB = tmp;
        }
        return paramA;
    }
    
    /**
     * 計算兩數的最小公倍數
     */
    public int getLeastCommonMultiple(int paramA, int paramB) {
        logger.info("paramA = " + paramA + ", paramB = " + paramB);
        int leastCommonMultiple = 0;
        leastCommonMultiple = paramA * paramB / getHighestCommonFactor(paramA, paramB);

        return leastCommonMultiple;
		}
		
}

單元測試的實作範例如下:

@SpringBootTest
@ExtendWith(MockitoExtension.class)
class DemoApplicationTests {

   private static Loggerlogger= Logger.getLogger("DemoApplicationTests");

   @InjectMocks
   public ExampleService exampleService;

   @Test
   void highestCommonFactorCalculateTest(){

			assertEquals(5, exampleService.getHighestCommonFactor(10, 5));
			assertEquals(15, exampleService.getHighestCommonFactor(15, 25));

   }

   @Test
   void leastCommonMultipleCalculateTest(){

			assertEquals(10, exampleService.getLeastCommonMultiple(10, 5));
			assertEquals(100, exampleService.getLeastCommonMultiple(15, 25));

   }
}

從上述的範例中可以看到,我們使用了 @InjectMocks 註解來測試 ExampleService 類別下的方法,代表我們將業務邏輯與框架中的其他層級分離了,從而實現業務邏輯的獨立測試。


上一篇
Day13 - Model中的業務邏輯 @Service(上)
下一篇
Day15 - Model中的資料存取層
系列文
這些年SpringBoot實戰開發教會我的事15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言