Posts

Java - Writing your own JUnit Rule

 Repost from  https://medium.com/@vanniktech/writing-your-own-junit-rule-3df41997b10c A JUnit Rule can be used to do some work around the execution of a test. One example would be to set up something before a test is running and then after it ran tearing something down. This is actually quite simple to do with JUnit itself. public class YourTest { @Before public void setUp() { // Do something before exampleTest starts. } @Test public void exampleTest() { // Your normal test. } @After public void tearDown() { // Do something after exampleTest finished. } } Now imagine you want to connect to a database during  setUp  and then close the connection in  tearDown . If you want to use that database in multiple files you don’t want to copy paste that code in every file. TestRule Let’s look at a quick example of a custom TestRule. public final class DatabaseRule implements TestRule { public Database database; @Override public Statement apply(f...

Java - Dependency Injection with Dagger 2

Image
Repost from  https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 Overview Many Android apps rely on instantiating objects that often require other dependencies. For instance, a Twitter API client may be built using a networking library such as  Retrofit . To use this library, you might also need to add parsing libraries such as  Gson . In addition, classes that implement authentication or caching may require accessing  shared preferences  or other common storage, requiring instantiating them first and creating an inherent dependency chain. If you're not familiar with Dependency Injection, watch  this  quick video. Dagger 2 analyzes these dependencies for you and generates code to help wire them together. While there are other Java dependency injection frameworks, many of them suffered limitations in relying on XML, required validating dependency issues at run-time, or incurred performance penalties during startup...