Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /******************************************************************************************
- * Example 1: How it is normally done.
- * This is bad because: hard to test, you depend on concrete classes and their details.
- *******************************************************************************************/
- public class HttpThing
- {
- public async string GetResponseAsString()
- {
- ... //details
- }
- }
- public class ClientCode
- {
- private HttpThing http = new() HttpThing;
- public string OperateWithResponse()
- {
- var thing = http.GetResponseAsString;
- // do something with thing
- return result;
- }
- }
- [Test]
- public class TestClientCode
- {
- [TestCase]
- public void TestOperateWithResponse()
- {
- // Now I have to initialize the whole thing if I want to test this code
- // and what if the response is different for whatever reason? What if I want to test and I don't have internet?
- }
- }
- /******************************************************************************************
- * Example 2: How it could be.
- * This is good because: Easy to test, you don't depend on details, it both has dependency injection and dependency inversion.
- *******************************************************************************************/
- public interface IHttpThing
- {
- async string GetResponseAsString();
- }
- public class HttpThing: IHttpThing
- {
- public async string GetResponseAsString()
- {
- //details, same as first example
- }
- }
- public class ClientCode
- {
- private IHttpThing http;
- public ClientCode(IHttpThing http)
- {
- this.http = http;
- }
- public string OperateWithResponse()
- {
- var thing = http.GetResponseAsString;
- // do something with thing
- return result;
- }
- }
- public class MockHttpThing: IHttpThing
- {
- public async string GetResponseAsString()
- {
- // I can set exactly what I expect to get
- return "{'something': [1, 2, 3], 'another_thing': true}"
- }
- }
- [Test]
- public class TestClientCode
- {
- public void TestOperationWithResponse()
- {
- var fakeHttp = new MockHttpThing();
- var client = new ClientCode(fakeHttp);
- // all my asserts and stuff that I can do in milisecond because I don't depend on anyone else.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement