iT邦幫忙

2021 iThome 鐵人賽

DAY 12
1

今天我們要對TWSIOpenService裡面的getDailyTranctionStockData方法進行測試
其實,在創立專案時應該就可以發現,Spring Boot會幫我們預設建立撰寫測試程式碼的
package位置,src/test/java-StockApiApplicationTests類別

先幫我在pom.xml加入

<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-test</artifactId>
		<scope>test</scope>
</dependency>

開啟我們StockApiApplicationTests類別

package com.stockAPI;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;



@SpringBootTest
class StockApiApplicationTests {

	@Test
	void contextLoads() {
		
	
}

此時我們只是單純要測試我們這個service的功能是否正常,我們可以這樣寫

package com.stockAPI;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.stockAPI.model.DailyTranctionStockData;
import com.stockAPI.service.TWSIOpenService;

@SpringBootTest
class StockApiApplicationTests {
	
	static Logger logger=LogManager.getLogger();
	
	@Autowired
	TWSIOpenService tWSIOpenService;

	@Test
	void contextLoads() {
		
	DailyTranctionStockData[] resultArray =tWSIOpenService.getDailyTranctionStockData();
	 if(resultArray!=null) {
		 for(DailyTranctionStockData data:resultArray) {
			 logger.info("code:"+data.getCode());
		 }
	 }
	 else {
		 logger.error("資料取得失敗");
	 }
	}
}

然後我們在這個頁面 按右鍵→Run As→Junit Test 就可以看到
https://ithelp.ithome.com.tw/upload/images/20210927/20138857BArZZXLMUI.png

接著我們在controller新增一個 url是從API取得的 上市個股日成交資訊

package com.stockAPI.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.stockAPI.model.APIReturnObject;
import com.stockAPI.model.DailyTranctionStockData;
import com.stockAPI.service.TWSIOpenService;

@RestController
@RequestMapping("stock/search")
public class StockSearchController {
	
	@Autowired
	TWSIOpenService tWSIOpenService;
	
	@GetMapping("exchange/getStockDayAll")
	public APIReturnObject getStockDayAll() {
		APIReturnObject aPIReturnObject = new APIReturnObject();
		Map<String, Object> data = new HashMap<String, Object>();
		DailyTranctionStockData[]  dailyTranctionStockDatas = tWSIOpenService.getDailyTranctionStockData();
		aPIReturnObject.setMessage("上市個股日成交資訊-取得成功");
		data.put("dailyTranctionStockDatas", dailyTranctionStockDatas);
		aPIReturnObject.setData(data);
		return aPIReturnObject;
		
	}

}

然後在securityConfig新增此連結的設定

package com.stockAPI.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.stockAPI.filter.JWTCheckFilter;
import com.stockAPI.service.StockUserService;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	StockUserService stockUserService;
	
	@Autowired
	JWTCheckFilter jWTCheckFilter;
	
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(stockUserService).
		passwordEncoder(new BCryptPasswordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http
    		.authorizeRequests()
    		.antMatchers("/user/create").permitAll() //管理員可以新增使用者資料
    		.antMatchers("/user/testUnblock").permitAll()
    		.antMatchers("/user/login").permitAll()
    		.antMatchers("/user/search/**").hasAnyAuthority("NORMAL","ADMIN") //取得用戶資料
    		.antMatchers("/user/stock/**").hasAnyAuthority("NORMAL","ADMIN") //取得股市資料
    		.and()
    		.addFilterBefore(jWTCheckFilter, UsernamePasswordAuthenticationFilter.class)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    		.and()
    		.csrf().disable();
        
    }
    
    //加密器註冊容器
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    //驗證類別註冊容器
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

接著就是在postman上進行測試

新增測試的collection&request
https://ithelp.ithome.com.tw/upload/images/20210927/20138857F4NfaeaUOK.png

按傳送後就可以看到結果囉!
https://ithelp.ithome.com.tw/upload/images/20210927/20138857l5YRAgoaiO.png


上一篇
RestTemplate實作(一)(Day11)
下一篇
Spring Boot定時任務排程器(DAY13)
系列文
Angular+Spring Boot API 處理股市資料32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言