Pages

Showing posts with label Unit Testing. Show all posts
Showing posts with label Unit Testing. Show all posts

Monday, March 9, 2020

Test creation order

Just digging into some old papers today, I found this old note. I think I did screenshot this long ago from a video by Sandro Mancuso. 

1. Class name: The class name is post fixed with Should. This is a pattern that was introduced by Sandro in his lectures. Since tests are probably already in the test package, we don't need to know post fix them with the word test, this class name is more BDD friendly and serves as good documentation.

2. Method name: Is concise and it explains what it does without revealing implementation detail. The words are separated with underscore so that it is easier to read than camel case in a first glance.

3. Assertion written first: By writing the assertion first we reduce the risk of introducing assumptions and over engineer. It helps keeping the code minimal and growing it progressively.

4. Action: Once  e have our assertion we will write the action. This maybe seems counter intuitive
but as you will notice, as we are writing the assertion and the action, the code is not compiling, this will force us to code the minimum required to make the test compile.

5. Setup: The last step is to add the setup. With this approach we forced our brain to focus on the behaviour and not on the state. This focus on behaviour is the key for growing the code gradually. Thinking on state first rather than behaviour can lead to assumptions and missed requirements.

This is a very interesting approach which has a lot of benefits. What do you think?

Monday, April 10, 2017

Mocking static method calls

Very simple example on how we can use method delegation to enable unit testing where there is a dependency to an static method call.



Thursday, April 6, 2017

Dealing with Hardwired dependencies part 2 - Making a design decission

In this second video, I make a design decision and I remove the temporary refactor that I did earlier.
The Seam was not a bad idea, but it was a temporary solution only until I make a decision about the design of the class.


Dealing with Hardwired dependencies part 1 - An alternative to Dependency injection.

In this video, I show a little refactoring trick that can be used to unit test a method that has a hardwired dependency to an external system via an static method call. This is an alternative approach to dependency injection, which can be used when we are not sure about modifying the design of the class. In very large systems making design decisions such as adding another method to a constructor etc ... may have a big impact in design of both production and test harnesses. This trick can help you temporarily postpone your design decision and get you going with your unit testing.



Monday, June 8, 2015

Stefan Birkner's system-rules library

Just a super quick post about an interesting library I just discovered :)

Its very rare the case when you will have to test things such as an String being printed in the console or a System property being set from the program... But in occasions it happens that.

Last week I discovered a library called system-rules, from Stefan Birkner. http://stefanbirkner.github.io/system-rules/
It is really interesting and easy to use, it can help you easily do tests that involve java.lang.System

Lets just quickly saw an example.
Imagine that for some reason you want to test that the console prints some message... I don't know you, but the only way I know to do that, is to redirect the stream that goes to the console, to something that you can control and read from(e.g a file, a log...). This kind of test would have lots of boiler plate. It would look somehow like this:

 @Test  
   public void consoleOutputOldSchoolTest() throws FileNotFoundException {  
     //Create some text file where the output will be redirected, so you can make an assertion later.  
     File testingFile = new File("testingFile.txt");  
     //Create a testing stream and give the file to it  
     PrintStream testingStream = new PrintStream(testingFile);  
     //Keep a copy of the old console output stream  
     PrintStream consoleStream = new PrintStream(System.out);  
     //Reset the object out to the new stream  
     System.setOut(testingStream);  
     //Write something to the "console"  
     System.out.print("test");  
     //Rewire back to the original console output  
     System.setOut(consoleStream);  
     //Just an informative message  
     System.out.println("all back to normal");  
     //Read the output that we are testing  
     String output = new Scanner(testingFile).nextLine();  
     //Do your assertion  
     assertThat(output, is("test"));  
     //Delete the test file  
     testingFile.delete();  
   }  

With Stefan's library you can test the messages that go the terminal in the blink of an eye:

   @Rule  
   public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();  
   @Test  
   public void systemRulesLibraryConsoleOutputTest() {  
     System.out.print("test");  
     assertThat(systemOutRule.getLog(), is("test"));  
   }  

Ok, now back to work now ;)

Monday, February 24, 2014

paranoia testing

Somebody told me once a funny story about a woman who day after day kept arriving late to work, because once on her way to the office, she kept having the need to go back home again and again just to check that she unplugged the iron from the wall socket. Her unfounded fear was such that one day she finally decided to take the iron with her to the office in her handbag.

A common unfounded fear that some developers sometimes have when working with the database, is that they will fail to query it for whatever reason and they feel the need of testing that the database is returning them the expected values. It is common to see horrible tests like this one:

   @Test  
   public void whenAddingANewUserTheUserIsSavedToTheDatabase() {  
     //Tell hibernate to add this user to the database   
     ormAdapter.add(userFactory("djordje", "123"));  
     //Find the user and check its values  
     User savedValueInDatabase = adapter.find("djordje");  
     assertThat(savedValueInDatabase.getName(),is("djordje"));  
     assertThat(savedValueInDatabase.getPassword(),is("123"));  
     //Delete the test data  
     ormAdapter.delete(savedValueInDatabase.getName());  
   }   

The above test has many problems, not just it is slow, also it is wrongly aimed because is not testing the functionality of the application, it just testing that some third party framework(hibernate in this case) is working properly.

Developers who do this, don't understand that the database is just a detail/add-on of the application.
It is fine to perform a smoke test to ping the database if they want(just to verify that the configuration of the ORM framework was correctly done), but testing that the HQL or the hibernate criteria are returning some values is wrong.
"Hibernate, MySQL, Oracle... all are just vendors, their solutions will work, you don't need to test them again!"

Focus on testing the functionality by mocking the dependencies you have with the database.
The only thing that counts at the end of the day is that the inputs and outputs to the service layer are processed correctly. If the data comes from a database, a file, a socket... doesn't matter at all.
Here an alternative test that will mock a dependency to the database and will check that the data is processed correctly:

   @Test  
   public void loginTest() {   
     PersonManagementAdapterORM adapterORM = mock(PersonManagementAdapterORM.class);  
     when(adapterORM.find("djordje","123")).thenReturn(new Person("djordje","123"));  
     LoginService service = new LoginServiceImpl(adapterORM);  
     boolean authorized = service.login("djordje","123");  
     verify(adapterORM).find("djordje","123");  
     assertThat(authorized,is(true));  
   }  

Now tests main concern is the functionality and not how the data is added to, or retrieved from the database.
I trained the mock to behave as expected and I verified that its behavoir was executed as expected.
The database was not at all a concern.

Thursday, May 23, 2013

How to verify that void methods were called using Mockito

You can also read this article in our brand new medium space. Click here!  Remember follow Javing on medium to make sure you don't miss out on some of the great new upcoming content.

Mockito is one of the most popular mocking frameworks for java.
This post Is just little miscellaneous where I will show you how to mock and verify a void method call.

Sometimes when we test a call to a void method all we want to do is just make sure that at some point in its life cycle, another method will be called with certain parameters.
Let's see the following example:
 public class SomeClass {  
      private OtherClass otherClass;  
     
      public SomeClass(OtherClass otherClass) {  
           this.otherClass = otherClass;  
      }  
      protected void firstMethod(int value) {  
           if(value > 0) {  
                secondMethod("Yes!");  
           }  
           else {  
                secondMethod("No!");  
           }  
      }  
      private void secondMethod(String value) {  
           otherClass.someMethod(value);  
      }       
 }  

In the above piece of legacy code the most important part is a method called "someMethod()". We must make sure that it is called in a proper way, but unfortunately it belongs to a dependency to which we have no access and also to make it more complicated it is inside a private method.

Mockito framework could help us mock and verify that method call.
Here is how we can do it:
 package demo;
 import static org.mockito.Mockito.verify;  
 import org.junit.Before;  
 import org.junit.Test;  
 import org.mockito.Mock;  
 import org.mockito.MockitoAnnotations;  
 import code.OtherClass;  
 import code.SomeClass;  
 public class TestClass {  
      @Mock  
      private OtherClass otherClass;  
      //Class under test  
      private SomeClass someClass;  
      @Before  
      public void prepareDependencies() {  
           MockitoAnnotations.initMocks(this);       
           someClass = new SomeClass(otherClass);  
      }  
      @Test  
      public void is_the_value_greater_than_zero() {  
           someClass.firstMethod(8);  
           verify(otherClass).someMethod("Yes!");  
      }  
      @Test  
      public void is_the_value_smaller_than_zero() {  
           someClass.firstMethod(-1);  
           verify(otherClass).someMethod("No!");  
      }  
 }  

The most important things to highlight in this test class are:
  • The class under test is never mocked.
  • The dependencies of the class under test need to be mocked.
  • By calling a method on a mock object we will mock that method call
  • By using the verify() method we will test that at some point the method from the mock was called  with the exact same parameters.
  • The test class can access the protected method because the package name is the same.(But of course in your project structure test will be under src/test/java and production code under src/main/java)

Share with your friends