top of page

Coffee and Tips Newsletter

Inscreva-se na nossa newsletter semanal

Nos vemos em breve!

How to create Mutation tests with Pitest

  • Writer: JP
    JP
  • Feb 7, 2021
  • 3 min read




Pitest is a tool that provides state-of-the-art mutation testing. It was written to run on Java applications or on applications that run on top of a JVM.


How it works?


Pitest works by generating mutant codes that will make changes to the bytecodes in the source code, changing logic, removing and even changing method return values. Thus, it's possible to evaluate the code in a more complete way, looking for failures and making the code reliable.


Basic example of mutation


See the code below:

if(name == ""){
   return "Empty name";
}else{
    return name;
}

Running Pitest on the code above, it's able to modify the bytecodes by changing the code above to:

if(name != ""){
   return name;
}else{
    return "Empty name";
}

Pitest enables you identifying possible points of failure and guide you to create tests based on these points.


Hands on time


Maven

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.pitest</groupId>
        <artifactId>pitest</artifactId>
        <version>1.6.2</version>
    </dependency>
</dependencies>

Let's create a simple class representing a bank account called BankAccount and to make it simple we'll implement the logic inside the entity class itself.


In this class, we have a method called userValid that checks if the user is valid.

package com.bank.entity;

public class BankAccount {

    public String bankName;
    public String user;
    public Double balance;

    public Boolean userValid(BankAccount bankAccount){
        if(bankAccount.user != ""){
            return true;
        }else{
            return false;
        }
    }
}

Without creating any test classes, run this command via Maven:

mvn org.pitest:pitest-maven:mutationCoverage

See that a report was generated in the console with the mutations created based on the conditions that must be tested.



Looking at the console above, we have 3 mutations or point of failures, which means we need to eliminate these mutations from our code.


Pitest provides another way to validate these mutations through a report generated by an HTML page. You can access these generated reports through /target/pit-reports/ folder


In the image below we can see a report that summarizes the coverage percentage. Note that we have 0% of coverage.

In the BankAccount.java.html file shows details about uncovered code parts.


Note that in the image above there is a list of Active mutators that are mutations based on the code we created.


Removing these mutations


Based on the reports, let's create some tests to reach out 100% of coverage. First of all, we need to create a class test. For this example, we're going to create a class test called BankAccountTest.java. To do this, there's an attention point.


You'll have to create this class with the same package's name used for the BankAccount.java. Thus, create inside src/test/java a package called com.bank.entity and finally BankAccountTest.java.


package com.bank.entity;

import org.junit.Assert;
import org.junit.Test;

public class BankAccountTest {


    @Test
    public void userValid_NegateConditionalsMutator_Test(){

        BankAccount bankAccount = new BankAccount(
                "Chase","Jonas", 2000.00);

        Boolean actual = bankAccount.userValid(bankAccount);
        Boolean expected = true;
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void userValid_BooleanFalseReturnValsMutator_Test(){

        BankAccount bankAccount = new BankAccount(
                "Chase","", 2000.00);

        Boolean actual = bankAccount.userValid(bankAccount);
        Boolean expected = false;
        Assert.assertEquals(expected, actual);
    }

}

We have created only 2 test method for our coverage:


1.userValid_NegateConditionalsMutator_Test(): Covers filled-in usernames. The constructor passed the "Chase" argument representing the username so that the method's condition is validated. And finally validates the condition of the method to be returned as TRUE.


To this case, we already eliminated two mutations according to statistic report.

  1. BooleanTrueReturnValsMutator

  2. NegateConditionalsMutator

2. userValid_BooleanFalseReturnValsMutator_Test(): Validates the possibility of the method returning the Boolean value FALSE.


Rerun the Maven command below:

mvn org.pitest:pitest-maven:mutationCoverage

Application console


Note that for every mutation generated, 1 was eliminated. Covering 100% coverage in tests.


References: https://pitest.org


Books to study and read


If you want to learn more about and reach a high level of knowledge, I strongly recommend reading the following book(s):


Unit Testing Principles, Practices, and Patterns: Effective Testing Styles, Patterns, and Reliable Automation for Unit Testing, Mocking, and Integration Testing with Examples in C# is a book that covers Unit Testing Principles, Patterns and Practices teaches you to design and write tests that target key areas of your code including the domain model. In this clearly written guide, you learn to develop professional-quality tests and test suites and integrate testing throughout the application life cycle.














Mastering Unit Testing Using Mockito and JUnit is a book that covers JUnit practices using one of the most famous testing libraries called Mockito. This book teaches how to create and maintain automated unit tests using advanced features of JUnit with the Mockito framework, continuous integration practices (famous CI) using market tools like Jenkins along with one of the largest dependency managers in Java projects, Maven. For you who are starting in this world, it is an excellent choice.














Well that’s it, I hope you enjoyed it!




5 Comments


melaniemarshall6592
9 hours ago

soicauxsmb.com mình thấy bạn bè nhắc mấy lần nên cũng bấm vào coi thử cho biết, kiểu tò mò giao diện thôi. Vào trang cái là thấy họ làm bố cục khá thoáng, không nhồi chữ dày đặc nên nhìn đỡ mệt mắt. Mình để ý cách họ chia nội dung theo từng khối rõ ràng, lướt xuống vẫn biết mình đang ở đoạn nào chứ không bị rối. Cái menu đặt ngay chỗ dễ thấy nên chuyển qua lại cũng nhanh, không phải mò nhiều. Nói chung cảm giác dùng khá nhẹ nhàng, nhất là mấy phần trình bày theo dạng cột nhìn gọn và dễ theo dõi trên màn hình. Mình thích nhất là các khối thông tin…

Like

savannapatt.er.s.on.7.0.4
5 days ago

https://de88.work/ mình tạt vào xem thử vì thấy có người nhắc, giao diện nhìn khá thoáng và không rối mắt. Mình không ngồi đọc từng chữ đâu, chủ yếu lướt qua để xem họ bố trí trang kiểu gì, thấy mọi thứ để đơn giản nên dễ định hướng. Ấn tượng nhất là cái khung “Recent Posts” đặt rõ ràng, nhìn phát biết ngay chỗ để xem bài mới. Nội dung thì vẫn kiểu bài mẫu “Welcome to WordPress…” nên cảm giác trang còn mới hoặc đang trong giai đoạn dựng lên. Nói chung mở lên vài phút là hiểu cách họ sắp xếp, vì phần “Recent Posts” hiện khá nổi và dễ thấy ngay trên trang.

Like

nolafo.wle156+abc123
Jul 09

luongsontv mình thấy bạn bè nhắc hoài nên tối qua bấm vào thử cho biết. Vừa vào là thấy trang nhẹ, bố cục gọn gàng kiểu ưu tiên cho người xem nhanh, kéo xuống là ra ngay mấy mục chính chứ không phải tìm vòng vòng. Mình không canh đúng giờ trận nào để xem hết, chỉ test lướt qua vài phút thôi nhưng cảm giác hình ảnh ổn, nhìn khá rõ trên điện thoại. Cái mình hay là phần tin tức thể thao cập nhật liên tục, tiêu đề nổi bật nên đọc lướt cũng bắt kịp diễn biến. Nói chung dùng nhanh, không bị rối mắt, và các khung thông tin được chia rõ ràng ngay trên giao…

Like

elsiebre.we.r1.6.921
Jun 29

sunwin mình ghé qua thử cho biết vì thấy bạn bè nói hoài, chứ cũng không định mò sâu gì. Vừa vào là thấy họ bố trí kiểu từng khối nội dung tách bạch, nhìn phát hiểu ngay chỗ nào là mục chính, chỗ nào chỉ là thông tin phụ. Mình thích cái cảm giác không bị “ngợp chữ”, cuộn xuống khá nhẹ tay, bấm qua lại cũng không bị giật lag gì, nhất là lúc mở bằng điện thoại. Nói chung mình chỉ lướt để xem cách họ sắp xếp thôi mà vẫn thấy dễ chịu, không phải căng mắt tìm nút hay đọc lan man. Mấy tiêu đề với ô nội dung được căn gọn theo dạng block…

Like

terrancecart.e.r.36.0.7
Jun 25

thefifaworldcups.com hôm bữa mình vào thử cho biết vì thấy mọi người nói nhiều, kiểu xem giao diện họ làm ra sao thôi. Mình không ngồi đọc hết nội dung, chủ yếu lướt qua cách họ sắp xếp thông tin kèo. Thấy ổn ở chỗ phần kèo bóng đá trực tuyến nhìn khá “thoáng”, chia mục rõ nên không bị rối mắt. Cái mình để ý nhất là bảng tỷ lệ hiển thị theo từng trận, nhìn một phát là thấy cột cả trận với hiệp 1 tách riêng, tiện cho ai chỉ muốn liếc nhanh. Cuộn trang cũng mượt, các khối nội dung dạng bảng xếp gọn gàng theo ngày nên nhìn vào là nhận ra ngay bảng tỷ…

Like
bottom of page