Am ajuns la testare. Cum faci testarea pentru WebAPI ? Simplu – in trei pasi
1. Creezi o clasa Data si o interfata IData care iti da datele. Clasa care foloseste API primeste o interfata IData. Clasa Data ia datele de pe WebAPI
2.. Testezi manual cu date reale si scrii datele pe hard
3. Faci o noua clasa , DataHard, ce implementeaza IData care iti citeste datele de pe hard.
4. Adaugi in proiectul de Test fisierele de date reale si DataHard
5. Clasa care foloseste API primeste ca interfata IData instanta de DataHard.
Cod:
Interfata de obtinere de date:
public interface IJsonData { Task<string> JsonData(int page = 1); }
Implementare cu WebAPI real si scriere pe hard a fisierelor
class JsonCountries : IJsonData { public async Task<string> JsonData(int page=1) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://api.worldbank.org/"); string req = "countries?format=json" +((page != 1) ? $"&page={page}" : ""); var response = await client.GetAsync(req); response.EnsureSuccessStatusCode(); var str= await response.Content.ReadAsStringAsync(); //System.IO.File.WriteAllText("countries" + page + ".txt", str); return str; } } }
Clasa care citeste de pe hard
class JsonCountriesFromHard : IJsonData { /// <summary> /// generating data with ///System.IO.File.WriteAllText("countries" + page + ".txt", str); /// </summary> /// <param name="page"></param> /// <returns></returns> public Task<string> JsonData(int page = 1) { return Task.FromResult( File.ReadAllText($@"Countries\countries{page}.txt")); } }
Clasa care va fi testata – primeste in constructor interfata
[assembly: InternalsVisibleTo("WorldBank.Test")] namespace WorldBank.Repository { public class CountriesRepository { private IJsonData data; public CountriesRepository():this(new JsonCountries()) { } internal CountriesRepository(IJsonData data) { this.data = data; } } }
Testarea manuala
var c = new CountriesRepository(); var data = c.GetCountries().Result; Console.WriteLine(data.Length);
Testarea automata
var c = new CountriesRepository(new JsonCountriesFromHard()); var data = c.GetCountries().Result; Assert.Equal(218, data.Length);
Gasiti tot codul la https://github.com/ignatandrei/WorldBankAPi
Intrebare – ca sa vad daca sunteti atenti: la ce foloseste InternalsVisibleTo ?
Pai e simplu 😛
Assembly-u WorldBank.Repository este expus doar lui WorldBank.Test
Pai… si daca vreau si din alta aplicatie?!