java-private-constructor-checker


Source link: https://github.com/pushtorefresh/java-private-constructor-checker

###Goal Max code coverage!

It means, that you need to test even private constructors of classes that must not be instantiated.

Q: Why would I want to test that constructor is private and that it throws exception??

A: Because if you are not the only developer in the project — others may change this (make constructor public, etc) and you may miss this on the code review because you are human).

A2: Because if you want to have as max code coverage as possible — you need to test even such unreacheable code.

###Sample Now, imagine you have such class with private constructor:

class Checks {

 private Checks() {

  throw new IllegalStateException("No instances please!");

}

 public static void checkNotNull(Object ref, String message) {

  if (ref == null) {

 throw new AssertionError(message);

  
}

}

 // other methods 
}

###The problem

Let's try to test this constructor!

@Test public void constructorMustBePrivateAndThrowException() {

try {

  new Checks();
 // won't compile! Constructor is private!
  fail("constructor must throw exception");

}
 catch (IllegalStateException expected) {

  assertEquals("No instances please!", expected.getMessage());

}
 
}

Okay, we can not just write a test for private constructor, we need reflection!

@Test public void constructorMustBePrivateAndThrowException() {

Constructor<?> constructor = Checks.class.getConstructor();

constructor.setAccessible(true);

 try {

  constructor.newInstance();

  fail("constructor must throw exception");

}
 catch (InvocationTargetException expected) {

  IllegalStateException cause = (IllegalStateException) expected.getCause();

  assertEquals("No instances please!", cause.getMessage());

}
 
}

And that's not even full code that you'll have to write, you also need to check that class does not have other constructors and some other things. So, you really want to write this boilerplate unreadable code every time?

###Clear solution

@Test public void constructorMustBePrivateAndThrowException() {

PrivateConstructorChecker
  .forClass(Checks.class) // Or you can use forClasses() and check multiple classes!
  .expectedTypeOfException(IllegalStateException.class)
  .expectedExceptionMessage("No instances please!")
  .check();
 
}

This is how we do! Clear, nice and readable!

What PrivateConstructorChecker does:

  • Checks that class has only one constructor without args and that it's private.
  • Checks that constructor throws exception (optional).
  • Can check exception type and/or exception message.
  • Saves you from boilerplate code!

###Download

Gradle:

testCompile 'com.pushtorefresh.java-private-constructor-checker:checker:1.2.0'

Maven:

<dependency>
  <groupId>com.pushtorefresh.java-private-constructor-checker</groupId>
  <artifactId>checker</artifactId>
  <version>1.2.0</version> </dependency>

Use, share, have fun!

Made with love in Pushtorefresh.com by @artem_zin and @nikitin-da

Resources

An easy to use wrapper of the native Android Snackbar which stays visible across multiple activities. It provides different themes to start with, and allows you to easily manage common scenarios like success, warning, error, info.

An easy file / folder picker dialog fragment which is easily to implement. Nothing special is required, you just need to add few lines of code!

This library add the ability to listen for drawable click events for TextView, EditText and AutoCompleteTextView normally added in XML with android:drawableStart etc... or in code with setCompoundDrawables(...) and similar.

With this library you can flat a layout used to side any widget with an ImageView or ImageButton added to listen for click on the icon, to one unique custom view.

SwipeableRV is a library that provides a fast and convenient way to implement the 'swipe to dismiss' feature in Recycler View, as seen in apps such as Messenger.

SwipeableRV wraps around ItemTouchHelper from the Android Support Library. Therefore, developers do not need to do any extra work on ItemTouchHelper.Callback themselves. Instead they can just focus on creating a recycler view, adapter, and view holder as normal, plus some minimal work on specifying some details such as supported swipe directions, deletion message or icon.

A custom view that gives the user a look and feel of selecting options with smoother slider animation.

With this SDK you can access the API behind the DRAE (Diccionario de la Real Academia Española, the official spanish dictionary) in order to use it in your own app.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes