示例#1
0
        [Test] // readFromURL returned wrong JSON
        public void TestGetPriceMalformedResponse()
        {
            //arrange
            var stockApi = StockAPIService.Instance();
            var dummy    = "dummy";

            //act

            _reader.ReadFromUrl(dummy).Throws(new Newtonsoft.Json.JsonReaderException());
            stockApi.Reader  = _reader;
            stockApi.APIPath = dummy;

            //assert
            Assert.Throws <Newtonsoft.Json.JsonReaderException>(() => stockApi.GetPrice("aapl"));
        }
        /// <summary>
        /// Get stock price from iex
        /// </summary>
        /// <param name="symbol">symbol Stock symbol, for example "aapl"</param>
        /// <returns>the stock price</returns>
        public double GetPrice(string symbol)
        {
            string url    = string.Format(_apiPath, symbol);
            string result = string.Empty;

            try
            {
                result = _reader.ReadFromUrl(url);
            }
            catch (Newtonsoft.Json.JsonReaderException ex)
            {
                Console.WriteLine(ex);
            }
            catch (Exception e)
            {
                Console.WriteLine("This is a web error");
                Console.WriteLine(e);
            }

            var    json  = JObject.Parse(result);
            string price = json.GetValue("price").ToString();

            return(double.Parse(price));
        }