Showing posts with label Spring-Boot. Show all posts
Showing posts with label Spring-Boot. Show all posts

Thursday, October 22, 2020

Gradle: Exclude SpringBoot Application Class from Jacoco Coverage

 

Jacoco plugin is a must if you care about not just writing random unit tests, but to ensure you have the right coverage for your code base. The plugin also comes with a report that shows the coverage at package level.

One thing that has been bothering me with SpringBoot apps I work with is the low number that always appears for the main SpringBoot Application class. This is a boiler plate class with a simple main method to launch the SpringApplication:

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Almost in every application we won't need to add any other additional logic to this method which makes it kind of dumb to create a test just to cover this class and main method. Best thing is to exclude it from our coverage using this format (in this case for Gradle):

jacocoTestReport {

    afterEvaluate {
        classDirectories.from = files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'com/mycom/shoppingcart/ServiceShoppingCartApplication.class')
        })
    }
}

Thursday, April 2, 2020

Spring REST Controller: Resolve conflicts between root controllers endpoints and swagger-ui.html


Our team had some issues setting up swagger. We've been adding swagger to multiple services and for a strange reason, one service was not loading the swagger-ui.html. After some testing, we realize there was a conflict with some endpoint that were mapping to the root of the site:

@RestController
public class ReportController {
    
    @RequestMapping(method = RequestMethod.GET, value = "/{reportId}")
    public ResponseEntity getReport(@PathVariable String reportId) {
        ....
    }
}

As we can see, since controller class has no request mapping, and endpoint method is mapping with /{some_id}, when we try to hit /swagger-ui.html, the request is mapped to this method.

After googling a lot, we ended up just making our request mapping more specific to a certain type of ids. In our case we are using mongo ids for the reports. It means ids can only have number or letters in lowercase.


@RestController
public class ReportController {
    
    @RequestMapping(method = RequestMethod.GET, value = "/{reportId:^[0-9a-f]+$}")
    public ResponseEntity getReport(@PathVariable String reportId) {
        ....
    }
}

Now because swagger-ui.html contains a dot (.) and a dash (-), the request is not being caught by this endpoint anymore.

Friday, June 14, 2019

Save binary files in MongoDB with Spring-Boot

Saving binary files in MongoDB is pretty simple with Spring-Boot. You simply need to put byte[] type in the CrudRepository entity:



public interface BinayFilesRepository extends MongoRepository<BinaryEntity, String> {

}

@Document(BinaryEntity = "binaries")
public class BinaryEntity {

    private String id;
    private byte[] data;

}

Tuesday, July 22, 2014

Spring: Integration testing under Spring Boot application context but mocking services


Use @MockBean annotation

DEPRACATED:

So I wanted to create some integration tests for an API application that uses Spring Boot. The thing is that I needed to load the same application context as the real applicationm, because Spring Boot performs a bunch of configurations for you, and these were not being loaded in a StandAlone mode.

But also I didn't want to use real services which depend upon real data. Depending on databases for your tests creates fragile tests.

After researching on the web I found this way:


This is the typical Spring-Boot entry point class.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

A base class having the logic to init the application context.

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = MyApplication.class)
public abstract class BaseIntegrationTest {

    protected MockMvc mockMvc;
    
    @Autowired
    protected WebApplicationContext wac;

    @Before
    public void setup() {
       
        MockitoAnnotations.initMocks(this);
        this.mockMvc = webAppContextSetup(wac).build();
    }
}

An implementation class mocking a required service class.
public class FooIntegrationTest extends BaseIntegrationTest {

    @Configuration
    public static class TestConfiguration {
        @Bean
        @Primary
        public FooService fooService() {
            return mock(FooService.class);
        }
    }


    @Autowired
    FooService mockFooService;
}