Friday, June 28, 2019

Building Java Applications with Gradle

Gradle wrapper:

  • In order to make sure you build the project with the same version of gradle as other developers (which can make a big difference), build the application using the wrapper: ./gradlew
    It will start with downloading the right gradle version, unless it's already there.
  • Watch out for running old gradlew for a version like 2.3 with a new java like version 11.  It quits silently without doing anything.

Useful commands:

  • gradle build -x test  -- run build but skip tests

Friday, June 7, 2019

Querying for Data in a Java Spring App - Alternatives


  1. Create a method with a name including all attributes you want to query by in your PersonRepository interface that implements CrudRepository<> (or PagingAndSortingRepository<>)
  2. Create a Specification object and use Spring findAll to find all records matching the Specification.
  3. Use @Query in the PersonRepository and define the query using JQL
  4. Use GraphQL (see for example https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.extensions.querydsl)

Monday, June 3, 2019

Unit testing with jUnit5 and Mockito

Mocking for Spring injected dependencies

import org.junit.jupiter.api.Test;

@ExtendWith(MockitoExtension.class)
class Person {
   @Mock
   DependencyA dependencyA;

   // Don't use @InjectMocks if using constructor injection with final dependencies.
   // Mockito can't set the new mocks for each test
   TestedClass target;

   @BeforeEach
   public void setup() {
      // only needed if you do Mockito.when(dependencyA.methodAbc()).thenReturn() or similar
      MockitoAnnotations.initialize(this);  
      target = new TestedClass(dependencyA);
   }

   @Test
   public void testMethodWhatsyourname() {
      // given
      ...
      
      // when
      target.whatsYourName();

      // then 
      ...
   }
}