Enoch Barcenas

Enoch Barcenas

1592627815

How to Test a Mock JNDI Datasource using Spring Framework

1. Overview

Typically, when testing an application that uses JNDI, we may want to use a mocked datasource instead of a real one. This is a common practice when testing in order to make our unit tests simple and fully separated from any external context.

In this tutorial, we’ll showcase how to test a mock JNDI datasource using the Spring Framework and the Simple-JNDI library.

2. Quick JNDI Recap

In short, JNDI binds logical names to external resources like database connections. The main idea is that the application doesn’t have to know anything about the defined datasource except its JNDI name.

Simply put, all naming operations are relative to a context, so to use JNDI to access a naming service, we need to create an InitialContext object first. As the name implies the InitialContext class encapsulates the initial (root) context that provides the starting point for naming operations.

In simple words, the root context acts as an entry point. Without it, JNDI can’t bind or lookup our resources.

3. How to Test a JNDI Datasource with Spring

Spring provides out-of-box integration with JNDI through SimpleNamingContextBuilder. This helper class offers a great way to mock a JNDI environment for testing purposes.

So, let’s see how we can use the SimpleNamingContextBuilder class to unit test a JNDI datasource.

First, we need to build an initial naming context for binding and retrieving the datasource object:

@BeforeEach
public void init() throws Exception {
    SimpleNamingContextBuilder.emptyActivatedContextBuilder();
    this.initContext = new InitialContext();
}

We’ve created the root context using the emptyActivatedContextBuilder() method because it provides more flexibility over the constructor, as it creates a new builder or returns the existing one.

Now that we have a context, let’s implement a unit test to see how to store and retrieve a JDBC DataSource object using JNDI:

@Test
public void whenMockJndiDataSource_thenReturnJndiDataSource() throws Exception {
    this.initContext.bind("java:comp/env/jdbc/datasource", 
      new DriverManagerDataSource("jdbc:h2:mem:testdb"));
    DataSource ds = (DataSource) this.initContext.lookup("java:comp/env/jdbc/datasource");
 
    assertNotNull(ds.getConnection());
}

As we can see_,_ we use the_ bind()_ method to map our JDBC DataSource object to the name java:comp/env/jdbc/datasource.

Then we use the lookup() method to retrieve a DataSource reference from our JNDI context using the exact logical name that we used previously to bind the JDBC DataSource object.

Note that, JNDI will simply throw an exception in case the specified object is not found in the context.

It’s worth mentioning that the_ SimpleNamingContextBuilder_ class is deprecated since Spring 5.2 in favor of other solutions such as Simple-JNDI.

#spring-framework #java #testing #developer

What is GEEK

Buddha Community

How to Test a Mock JNDI Datasource using Spring Framework
Joseph  Murray

Joseph Murray

1621492530

7 Test Frameworks To Follow in 2021 for Java/Fullstack Developers

It is time to learn new test frameworks in 2021 to improve your code quality and decrease the time of your testing phase. Let’s explore 6 options for devs.

It is time to learn new test frameworks to improve your code quality and decrease the time of your testing phase. I have selected six testing frameworks that sound promising. Some have existed for quite a long time but I have not heard about them before.

At the end of the article, please tell me what you think about them and what your favorite ones are.

Robot Framework

Robot Framework is a generic open-source automation framework. It can be used for test automation and robotic process automation (RPA).

Robot Framework is open and extensible and can be integrated with virtually any other tool to create powerful and flexible automation solutions. Being open-source also means that Robot Framework is free to use without licensing costs.

The RoboFramework is a framework** to write test cases and automation processes.** It means that it may replace** your classic combo Selenium + Cucumber + Gherkins**. To be more precise, the Cucumber Gherkins custom implementation you wrote will be handled by RoboFramework and Selenium invoked below.

For the Java developers, this framework can be executed with Maven or Gradle (but less mature for the latter solution).

#java #testing #test #java framework #java frameworks #testing and developing #java testing #robot framework #test framework #2021

Were  Joyce

Were Joyce

1623424020

Spring Framework Tutorial

What is the spring framework in Java?

The spring framework is one of the most versatile frameworks in java which is used to bring down the complexity of the development of enterprise-grade applications. The first production release of the spring framework was in March 2004 and since then, this robust and open-source framework has gained tremendous popularity, so much so that it is often referred to by developers all around the world as the “framework of frameworks”. Spring is a loosely coupled, open-source application framework of java. It is lightweight and the inversion of the control container for the Java platform. A large number of Java applications use the core features of the spring framework. In addition to that, extensions have also been developed to allow developers to develop Web Applications on top of the Java Enterprise Edition platform.

#spring #spring-framework #java #spring framework tutorial #why should one learn about the spring framework? #what is the spring framework in java?

Lindsey  Koepp

Lindsey Koepp

1598948520

Top 10 Test Automation Frameworks in 2020

We are moving toward a future where everything is going to be autonomous, fast, and highly efficient. To match the pace of this fast-moving ecosystem, application delivery times will have to be accelerated, but not at the cost of quality. Achieving quality at speed is imperative and therefore quality assurance gets a lot of attention. To fulfill the demands for exceptional quality and faster time to market, automation testing will assume priority. It is becoming necessary for micro, small, and medium-sized enterprises (SMEs) to automate their testing processes. But the most crucial aspect is to choose the right test automation framework. So let’s understand what a test automation framework is.

What Is a Test Automation Framework?

A test automation framework is the scaffolding that is laid to provide an execution environment for the automation test scripts. The framework provides the user with various benefits that help them to develop, execute, and report the automation test scripts efficiently. It is more like a system that was created specifically to automate our tests. In a very simple language, we can say that a framework is a constructive blend of various guidelines, coding standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data injections, etc. to pillar automation testing. Thus, the user can follow these guidelines while automating applications to take advantage of various productive results.

The advantages can be in different forms like the ease of scripting, scalability, modularity, understandability, process definition, re-usability, cost, maintenance, etc. Thus, to be able to grab these benefits, developers are advised to use one or more of the Test Automation Framework. Moreover, the need for a single and standard Test Automation Framework arises when you have a bunch of developers working on the different modules of the same application and when we want to avoid situations where each of the developers implements his/her approach towards automation. So let’s have a look at different types of test automation frameworks.

Types of Automated Testing Frameworks

Now that we have a basic idea about Automation Frameworks, let’s check out the various types of Test Automation Frameworks available in the marketplace. There is a divergent range of Automation Frameworks available nowadays. These frameworks may differ from each other based on their support to different key factors to do automation like reusability, ease of maintenance, etc.

Types of Test Automation Frameworks:

  1. Module Based Testing Framework
  2. Library Architecture Testing Framework
  3. Data-Driven Testing Framework
  4. Keyword Driven Testing Framework
  5. Hybrid Testing Framework
  6. Behavior Driven Development Framework

Benefits of a Test Automation Framework

Apart from the minimal manual intervention required in automation testing, there are many advantages of using a test automation framework. Some of them are listed below:

  1. Faster time-to-market: Using a good test automation framework helps reduce the time-to-market of an application by allowing constant execution of test cases. Once automated, the test library execution is faster and runs longer than manual testing.
  2. Earlier detection of defects: The documentation of software defects becomes considerably easier for the testing teams. It increases the overall development speed while ensuring correct functionality across areas. The earlier a defect is identified, the more cost-effective it is to resolve the issue.
  3. Improved Testing efficiency: Testing takes up a significant portion of the overall development lifecycle. Even the slightest improvement of the overall efficiency can make an enormous difference to the entire timeframe of the project. Although the setup time takes longer initially, automated tests eventually take up a significantly lesser amount of time. They can be run virtually unattended, leaving the results to be monitored toward the end of the process.
  4. Better ROI: while the initial investment may be on the higher side, automated testing saves organizations many a lot of money. This is due to the drop in the amount of time required to run tests, which leads to a higher quality of work. This in turn decreases the necessity for fixing glitches after release, thereby reducing project costs.
  5. Higher test coverage: In test automation, a higher number of tests can be executed about an application. This leads to higher test coverage, which is a manual testing approach that would imply a massive team, limited heavily with their amount of time. An increased test coverage leads to testing more features and a better quality of the application.
  6. Reusability of automated tests: The repetitive nature of test cases in test automation helps software developers to assess program reaction, in addition to the relatively easy configuration of their setup. Automated test cases can be utilized through different approaches as they are reusable.

#devops #testing #software testing #framework #automation testing #mobile app testing #test framework

Enoch Barcenas

Enoch Barcenas

1592627815

How to Test a Mock JNDI Datasource using Spring Framework

1. Overview

Typically, when testing an application that uses JNDI, we may want to use a mocked datasource instead of a real one. This is a common practice when testing in order to make our unit tests simple and fully separated from any external context.

In this tutorial, we’ll showcase how to test a mock JNDI datasource using the Spring Framework and the Simple-JNDI library.

2. Quick JNDI Recap

In short, JNDI binds logical names to external resources like database connections. The main idea is that the application doesn’t have to know anything about the defined datasource except its JNDI name.

Simply put, all naming operations are relative to a context, so to use JNDI to access a naming service, we need to create an InitialContext object first. As the name implies the InitialContext class encapsulates the initial (root) context that provides the starting point for naming operations.

In simple words, the root context acts as an entry point. Without it, JNDI can’t bind or lookup our resources.

3. How to Test a JNDI Datasource with Spring

Spring provides out-of-box integration with JNDI through SimpleNamingContextBuilder. This helper class offers a great way to mock a JNDI environment for testing purposes.

So, let’s see how we can use the SimpleNamingContextBuilder class to unit test a JNDI datasource.

First, we need to build an initial naming context for binding and retrieving the datasource object:

@BeforeEach
public void init() throws Exception {
    SimpleNamingContextBuilder.emptyActivatedContextBuilder();
    this.initContext = new InitialContext();
}

We’ve created the root context using the emptyActivatedContextBuilder() method because it provides more flexibility over the constructor, as it creates a new builder or returns the existing one.

Now that we have a context, let’s implement a unit test to see how to store and retrieve a JDBC DataSource object using JNDI:

@Test
public void whenMockJndiDataSource_thenReturnJndiDataSource() throws Exception {
    this.initContext.bind("java:comp/env/jdbc/datasource", 
      new DriverManagerDataSource("jdbc:h2:mem:testdb"));
    DataSource ds = (DataSource) this.initContext.lookup("java:comp/env/jdbc/datasource");
 
    assertNotNull(ds.getConnection());
}

As we can see_,_ we use the_ bind()_ method to map our JDBC DataSource object to the name java:comp/env/jdbc/datasource.

Then we use the lookup() method to retrieve a DataSource reference from our JNDI context using the exact logical name that we used previously to bind the JDBC DataSource object.

Note that, JNDI will simply throw an exception in case the specified object is not found in the context.

It’s worth mentioning that the_ SimpleNamingContextBuilder_ class is deprecated since Spring 5.2 in favor of other solutions such as Simple-JNDI.

#spring-framework #java #testing #developer

Roberta  Ward

Roberta Ward

1602765064

Use Mocks in Testing? Choose the Lesser Evil!

Mocking Test Methodology

The key idea of mocking is to replace real code (e.g. calls to a database or service) with artificial functionality that has the same return type. There are different approaches in this practice. Here, I explain best practices and why it might be better to avoid mocking in order to have real code quality.

User Service - Example to Be Tested With Mocks

Let’s write simple application that fetch users from http service.

Java

public Optional<User> createUser(String name) {
        try {
            //Preparation of request: auth, body and media type of request
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(APPLICATION_JSON);
            headers.set("auth", "mySecretKey");
            //Specifying body
            HttpEntity<String> request =
              new HttpEntity<String>("{\"name\":" + name + "}", headers)
            //Making request with and deserializing response into User object
            User newUser = (new RestTemplate()).postForEntity("/server/users",                                                      request, User.class).getBody();
            newUser.setIssueDate(Date.now());
            return Optional.of(newUser);
        } catch (Exception e) {
            System.out.println("Something went wrong! : " + e.getMessage());
            Return Optional.empty();
        }
}
@Data
class User {
    private Integer id;
    private String name;
    private Date issueDate;
}

Implementation Details

The method, createUser, basically does 4 things:

  1. Preparation of request: authentication, preparing body and media type of request (line 4-5 corresponding to 1, 2, 3 step on the diagram.
  2. Making request to server with given url (line 11 or step 4).
  3. Receiving the response and deserializing it into an object. (line 11- yes the same line! and step 9 on diagram).
  4. Setting the current date to created user (line 12, or step 10).

The remaining actions are done on server-side and hidden from application:

1. Server check that body has json type and correct auth key (step 5,6).

2. Make business logic (create a user) (step 7).

3. Generate response with new user id (step 8).

createUser workflow

#performance #testing #spring #mockito #powermock #mock #http server #http testing