Java test class methods

Java test class methods

  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • How to maintain polyglot persistence for microservices Managing microservice data may be difficult without polyglot persistence in place. Examine how the strategy works, its challenges.
  • GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • The basics of implementing an API testing framework With an increasing need for API testing, having an efficient test strategy is a big concern for testers. How can teams evaluate .
  • The potential of ChatGPT for software testing ChatGPT can help software testers write tests and plan coverage. How can teams anticipate both AI’s future testing capabilities .
  • 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • Prices for cloud infrastructure soar 30% Tough macroeconomic conditions as well as high average selling prices for cloud computing and storage servers have forced .
  • API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
  • Risk & Repeat: Are data extortion attacks ransomware? Ransomware gangs are focusing more on data theft and extortion while skipping the encryption of networks. But should these .
  • Cyber insurers adapting to data-centric ransomware threats Cyber insurance carriers and infosec vendors weigh in on how the shift in ransomware tactics is affecting policies and coverage, .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Читайте также:  Вертикальное адаптивное многоуровневое меню css

Источник

Testing an Abstract Class With JUnit

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll analyze various use cases and possible alternative solutions to unit-testing of abstract classes with non-abstract methods.

Note that testing abstract classes should almost always go through the public API of the concrete implementations, so don’t apply the below techniques unless you’re sure what you’re doing.

2. Maven Dependencies

Let’s start with Maven dependencies:

 org.junit.jupiter junit-jupiter-engine 5.9.2 test  org.mockito mockito-core 2.8.9 test  org.powermock powermock-module-junit4 1.7.4 test  junit junit    org.powermock powermock-api-mockito2 1.7.4 test 

You can find the latest versions of these libraries on Maven Central.

Powermock isn’t fully supported for Junit5. Also, powermock-module-junit4 is used only for one example presented in section 5.

3. Independent Non-Abstract Method

Let’s consider a case when we have an abstract class with a public non-abstract method:

public abstract class AbstractIndependent < public abstract int abstractFunc(); public String defaultImpl() < return "DEFAULT-1"; >>

We want to test the method defaultImpl(), and we have two possible solutions – using a concrete class, or using Mockito.

3.1. Using a Concrete Class

Create a concrete class which extends AbstractIndependent class, and use it to test the method:

public class ConcreteImpl extends AbstractIndependent < @Override public int abstractFunc() < return 4; >>
@Test public void givenNonAbstractMethod_whenConcreteImpl_testCorrectBehaviour()

The drawback of this solution is the need to create the concrete class with dummy implementations of all abstract methods.

3.2. Using Mockito

Alternatively, we can use Mockito to create a mock:

@Test public void givenNonAbstractMethod_whenMockitoMock_testCorrectBehaviour()

The most important part here is the preparation of the mock to use the real code when a method is invoked using Mockito.CALLS_REAL_METHODS.

4. Abstract Method Called From Non-Abstract Method

In this case, the non-abstract method defines the global execution flow, while the abstract method can be written in different ways depending upon the use case:

public abstract class AbstractMethodCalling < public abstract String abstractFunc(); public String defaultImpl() < String res = abstractFunc(); return (res == null) ? "Default" : (res + " Default"); >>

To test this code, we can use the same two approaches as before – either create a concrete class or use Mockito to create a mock:

@Test public void givenDefaultImpl_whenMockAbstractFunc_thenExpectedBehaviour()

Here, the abstractFunc() is stubbed with the return value we prefer for the test. This means that when we call the non-abstract method defaultImpl(), it will use this stub.

5. Non-Abstract Method With Test Obstruction

In some scenarios, the method we want to test calls a private method which contains a test obstruction.

We need to bypass the obstructing test method before testing the target method:

public abstract class AbstractPrivateMethods < public abstract int abstractFunc(); public String defaultImpl() < return getCurrentDateTime() + "DEFAULT-1"; >private String getCurrentDateTime() < return LocalDateTime.now().toString(); >>

In this example, the defaultImpl() method calls the private method getCurrentDateTime(). This private method gets the current time at runtime, which should be avoided in our unit tests.

Now, to mock the standard behavior of this private method, we cannot even use Mockito because it cannot control private methods.

Instead, we need to use PowerMock (note that this example works only with JUnit 4 because support for this dependency isn’t available for JUnit 5):

@RunWith(PowerMockRunner.class) @PrepareForTest(AbstractPrivateMethods.class) public class AbstractPrivateMethodsUnitTest < @Test public void whenMockPrivateMethod_thenVerifyBehaviour() < AbstractPrivateMethods mockClass = PowerMockito.mock(AbstractPrivateMethods.class); PowerMockito.doCallRealMethod() .when(mockClass) .defaultImpl(); String dateTime = LocalDateTime.now().toString(); PowerMockito.doReturn(dateTime).when(mockClass, "getCurrentDateTime"); String actual = mockClass.defaultImpl(); assertEquals(dateTime + "DEFAULT-1", actual); >>

Important bits in this example:

  • @RunWith defines PowerMock as the runner for the test
  • @PrepareForTest(class) tells PowerMock to prepare the class for later processing

Interestingly, we’re asking PowerMock to stub the private method getCurrentDateTime(). PowerMock will use reflection to find it because it’s not accessible from outside.

So, when we call defaultImpl(), the stub created for a private method will be invoked instead of the actual method.

6. Non-Abstract Method Which Accesses Instance Fields

Abstract classes can have an internal state implemented with class fields. The value of the fields could have a significant effect on the method getting tested.

If a field is public or protected, we can easily access it from the test method.

But if it’s private, we have to use PowerMockito:

public abstract class AbstractInstanceFields < protected int count; private boolean active = false; public abstract int abstractFunc(); public String testFunc() < if (count >5) < return "Overflow"; >return active ? "Added" : "Blocked"; > >

Here, the testFunc() method is using instance-level fields count and active before it returns.

When testing testFunc(), we can change the value of the count field by accessing instance created using Mockito.

On the other hand, to test the behavior with the private active field, we’ll again have to use PowerMockito, and its Whitebox class:

@Test public void whenPowerMockitoAndActiveFieldTrue_thenCorrectBehaviour()

We’re creating a stub class using PowerMockito.mock(), and we’re using Whitebox class to control object’s internal state.

The value of the active field is changed to true.

7. Conclusion

In this tutorial, we’ve seen multiple examples which cover a lot of use cases. We can use abstract classes in many more scenarios depending upon the design followed.

Also, writing unit tests for abstract class methods is as important as for normal classes and methods. We can test each of them using different techniques or different test support libraries available.

The full source code is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью