RestTemplate实作(二)(Day12)

今天我们要对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


<<:  Alpine Linux Porting (一点六?)

>>:  个 人 工 作 室 台 湾 本 土 妹 免 房 费 可 外 约 到 家 旅 馆

Day 24 - PVE 修复 Loading initial ramdisk

今天笔者遇到一个问题,系统在开机时卡在 “Loading initial ramdisk”,用了一些...

鬼故事 - 我们有通过国际资安 OOO 标准

鬼故事 - 我们有通过国际资安 OOO 标准 credit: AilinStock, DNDmeme...

Day 22: 元件原则 — 内聚性 (待改进中... )

「如果 SOLID 原则告诉我们的是如何将砖块安排到墙壁和房间中,那麽元件原则就是告诉我们,如何将...

D20. 学习基础C、C++语言

D20. 字串题练习 这题是之前老师出的题目但是我一直解不出来,後来看很久,还跑去问同学才解出来的,...

好的履历是面试的入门票

标题开头可能大家读起来不就是废话吗,履历怎麽写,Google 关键字详细到有成千上万页的各种样式可做...