Category Archives: Java

Week 12 – Comparing Tips

For this week, I wanted to look at what some websites consider helpful tips when it comes to testing software in Java and compare that to what we have learned in class. By looking at each tip one by one and comparing it to the things Professor Wurst has taught us during our lectures.

For this, I will be looking at this website: https://www.code-intelligence.com/blog/11-tips-unit-testing-java

Tip Number 1 is to “Compose Tests before Writing Code”, which is actually what we have been focusing upon for the last few weeks, so it’s good to see that this is being reaffirmed

Number 2: Keep tests small and concentrated. This is another subject that we’ve been looking at as well, as we’ve been looking at strategies on how to concatenate code for test.

Number 3: Defining your Code Coverage. This isn’t actually something I believe we’ve spoken about in this class, however, we have discussed similar things in my previous classes with Process Management.

Number 4: Isolating Tests from External Sources. This one Im not sure if we have discussed it, but it also seems like a given, considering we have been taught to always only use tests in test classes and to pull from testing packages when importing.

Number 5: Automate wherever possible. I don’t actually think we’ve done this yet in Testing, however, this is something we have discussed previously in another class, I believe in Software Design. If you can automate something, always try to.

Number 6: Creating Mock Dependencies. This isn’t something in specific we’ve touched upon yet I feel, however it makes sense. I feel as though when I did our first homework, I kind of did something similar to this.

Number 7: Use Assertions. Yes. Absolutely we have done this in class. All if not most classes we have written use assert.equals(), assert.true(), or assert.false(), amongst others.

Number 8: Using proper names to test methods. This is something we learned way back in CS101. Always name your methods something understandable for you and your team to instantly know what it does. Never write gobbledygook names for methods, be concise.

Number 9: Keep Unit Tests Up to Date. I don’t believe this has been taught yet as most code we have worked with has been static and unchanging. However, Im sure we will have assignments where we focus on this harder. It definitely seems like something that is extremely important, as code changes so too should the tests, or else they wont work properly or even give false positives.

Number 10: Don’t Focus on Implementation. This one is interesting to me. We haven’t really spoken about implementation of code when it comes to testing. It’s very interesting to me because I have never really thought about this before, but it definitely makes a lot of sense to me. Something good to keep in mind for the future.

And lastly number 11: Create independent test cases. I actually unfortunately learned this myself the hard way with the first homework, as each class was accidentally dependent of one another if ran back to back. It’s something I definitely need to keep in mind going forwards.

And thats it! It’s definitely a lot of overlap which is great to see. Until next week!

From the blog CS@Worcester – You're Telling Me A Shrimp Wrote This Code?! by tempurashrimple and used with permission of the author. All other rights reserved by the author.

Week 10 Blog Post

Searching for an article this week I looked for something relating to mocking. Considering last week I did the negatives on mocking I think it’s valuable to have various perspectives. Seeing multiple ideas with mocking can give us an idea of how to implement them in the future. The writer of this article is a reliable source being a Java script developer. Getting information from someone in the industry can give a perspective inside the workforce and how people inside see different ideas. Not everyone may agree with using the same coding language but seeing how developers see different concepts can give an idea of the drawbacks to stuff and where in our own experiences can we improve. Overall this article is a great way to see how mocking is seen inside the workforce by an experienced professional.   

In this article, Eric Elliot focuses on the drawbacks of excessive mocking. He points out how brittle tests and how they can be easily broken. There broken simply just from the change of implementation even though the behavior stays the same. Another point is a false sense of security because of there lack of accuracy that occurs from not using accurate real behavior. This is a fault in the test because the test will pass even if it isn’t supposed to. Third, he focuses on complexity overload which is just adding too much complexity can make the code harder to understand and maintain. Elliot still believes in mocking but a more balanced approach can overall help the program. Mocking should be used sparingly and when there actual weight for its use. All together Elliott wants the audience to create a strategy that will have confidence in their code correctness while also minimizing any negatives of excessive mocking. 

Reading this article at first I thought it would be more of a pro mocking but it’s more in between. It says its flaws while still sharing the positives. After reading this article I understand that mocking can cut time but it can bring flaws to testing. The best time to utilize mocking is when time is scarce and later it can updated with time. It still isn’t the ultimate be-all to testing but with a balance, it will work. Understanding these flaws can foresee issues that may come up when mocking. Mocking should never bring up complexities that can complicate the code and should always have a priority in simple to understand and easy maintenance.

https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a

From the blog CS@Worcester – DCO by dcastillo360 and used with permission of the author. All other rights reserved by the author.

Week 9 Blog Post

Choosing a topic for this week I tried to find something we had recently touched upon. Last week we went over mocking and expanding my knowledge of this topic can benefit me and the class. Searching for articles about mocking I stumbled upon one that shares the negatives of using mocking data. To counter-attack the ideas we learned in class it is always great to know both sides to using a concept. 

This article doesn’t fully dispose of mocking but gives ideas when it’s good to use. It gives a variety of examples including “Isolating the unit under test from other components or dependencies that are not relevant to the test, Speeding up the test execution by avoiding network calls or database queries that can be slow or unreliable, and Controlling the test input and output by creating predictable and consistent data that can be easily verified”. These ideas are then counterposed to the negatives such as “Introducing errors or inconsistencies between the mock data and the real data, which can lead to false positives or false negatives in the test results, Reducing the coverage and confidence of the test, by not testing the actual behavior and logic of the external source or the interaction with it, and Increasing the maintenance and complexity of the test, by requiring extra code and logic to create and manage the mock data”. The flaws of mocking data are mainly it does not use real data making it much more different from the real data creating disparities between the two. These tests ignore scenarios with much more complexity and these error and bugs can go unseen. The author assures the reader to use a data source to improve the tests.

After reading this article it gave me insight into the negatives of using mocking. The week prior activities made the use of mocking reduce time in creating classes but it’s good to know when it should be used and when it shouldn’t. I wish there was a perfect solution for every test but to find bugs in your code you must expand your horizon. Reading this article made me see that a variety of tests testing different things can overall benefit you. You never have to completely ignore a type of test but being able to see the positives and negatives can save you in the long run. Plus it will allow you to have a broader knowledge knowing that this may have flaws but there are things I can add to have a satisfactory end product.       

https://medium.com/@queenskisivuli/why-mocking-data-is-a-bad-practice-for-testing-a20d2d7104aa

From the blog CS@Worcester – DCO by dcastillo360 and used with permission of the author. All other rights reserved by the author.

Pairwise and Combinatorial Testing

The article “Combinatorial Testing” focuses on the insights of software testing methods. This article explores the evolution of combinatorial testing, talking about advancements in algorithm performance and constraint representation. The article also talks about the importance in detecting interaction failures within software systems. The article also demonstrates the effectiveness of t-way combinations fault detection across various domains. The article “Pairwise Testing” talks about pair testing as a permutation and combination technique aimed at testing each pair of input parameters to ensure that the system if functioning properly across all possible combinations. The article also addresses the many benefits of pairwise testing and it’s role in reducing test execution time and cost while maintaining test coverage. Also, it talks about the challenges associated with pairwise testing, including the limitations in detecting interactions beyond pairwise combinations.

Pairwise Testing

pairwise testing is a software testing method that aims to comprehensively validate the behavior of a system by testing all possible pairs of input parameters. This method is mainly used when many of the defects in software systems are triggered by interactions between pairs of input parameters, rather than by individual parameters in isolation.

Benefits & Challenges

some benefits that pairwise offers is, efficiency: by testing the combinations of two input parameters at a time. This reduce’s the number of test cases required compared to exhaustive testing. pairwise testing also offers effective defect detection: by effectively finding defects that are triggered by interactions between pairs of input parameters, pairwise testing also helps to identify certain scenarios by systematically exploring pairs of parameters. Some challenges that pairwise testing may face is when it comes to parameter selection. Selecting the right parameters is crucial and requires a lot of knowledge of the software and it’s potential interaction scenarios. If the wrong parameter is selected this can lead to incomplete test coverage and missed defects.

Combinatorial Testing

Combinatorial testing is a software testing technique that focuses on efficiently testing the interactions between different input parameters of a system. This test method involves generating a set of test cases that include various combinations of input values / specific parameter values.

Benefits & Challenges

Some benefits of combinational testing include improved software quality: by being able to identify and address the interaction failures early in the development process. This test method tests various combinations of input parameters, which can help find defects that could impact the systems performance. A challenge that combinational testing may face is the scalability. Combinatorial testing is effective for small to medium sized systems and when scaling it to large and complex systems with a high number of input parameters and values, you may run into some problems.

Why did I pick this Article?

I pick these two article that talk about pairwise and combinatorial testing because both these test methods stand at the forefront of software test methods. The article’s goes into details about how both of these test methods offer an efficient way to ensure comprehensive test coverage while minimizing redundancy. Both of these articles have taught me a lot about pairwise and combinational testing.

Reflection

After reading both of these articles, I have gained a greater understanding of both these test cases. With the new found knowledge, I aspire to apply pairwise and combinatorial testing techniques in my future projects. Both these test methods offer practical solutions to common testing challenges, and by incorporating them into my future endeavors I aim to contribute to the development of reliable software systems.

Article link is here: https://www.sciencedirect.com/science/article/abs/pii/S0065245815000352

https://testsigma.com/blog/pairwise-testing/

From the blog CS@Worcester – In's and Out's of Software Testing by Jaylon Brodie and used with permission of the author. All other rights reserved by the author.

Understanding Test Driven Development in Software Engineering

Test Driven Development is a method in software development in which tests are created before the actual code. By writing test before hand, developers have a clear understanding of what will need to implemented, which can help avoid unnecessary errors. This approach will help to have the software behave as expected. This method is a structured and systematic approach. This test method is doesn’t just focus on testing, however it also focuses on quality and behavior. The main goal of this test method is to ensure that the code meets the specified requirements and behaves as expected. Test Driven Development helps with clarifying requirements, reducing defects, and improving the code maintainability.

How does it work?

Test Driven Development operates on a cycle like, first write a test, second make it run, third change the code to make it pass, and then repeat. Developers should first write a test that will analyze the behavior that they want implement. After running the test and writing and rewriting the code to make the test pass, developers will then need to continue reframing the code to improve it’s design and maintainability without changing it’s behavior. This process will make sure that that each piece of code is throughly tested and validate before moving on to the next.

Test Driven Development vs Traditional Testing

The difference between Test Drive Development and Traditional testing is that test driven development method has a different approach and objective. Traditional testing methods usually aim to find bugs or even defects in code, test driven development mainly focuses on making sure that the code meets the specific requirements. A failed test in test driven development method tells the developers to write new code to fulfill the requirement’s, and it also tends to make sure that the code will be lead to higher quality, with fewer defects.

There are also two levels of test driven development that focuses on different aspects of software development. Those two levels being Acceptance TDD and Developer TDD. Acceptance involves writing acceptance test that verify the overall behavior of the systems based on the users requirements. Development TDD, focuses on writing unit tests for individual components or modules of the system.

Why Did I pick this Article?

I chose this article because Test Driven Development is a very important concept in software engineering. This article has taught me a lot about test driven development , which include numerous benefits like improved quality of code, reduced bugs and fewer defects, and faster development cycle. These many advantages are valuable for any software development project.

Reflection

After reading this article, i have learned a lot about Test Driven Development and it’s many advantages. One key take away for me was how in this method developers are to write test before actually writing the code, which can help in clarifying and ensuring that the code is correct and meets the required specifications. I also found how the article talks about the difference between test driven development and traditional testing methods. Learning about the Acceptance TDD framework helped me with my understanding of how test drive development can be scaled for larger projects and integrated into Acceptance methods.

Now that my understanding has been enlighten with this new found valuable knowledge and insights into test driven development methods, I can apply this in my future software development projects. I will also be able to writer better, cleaner, and more maintainable code when using this method.

Article link is Here: https://www.guru99.com/test-driven-development.html

From the blog CS@Worcester – In's and Out's of Software Testing by Jaylon Brodie and used with permission of the author. All other rights reserved by the author.

Getting Started With Python Unit Testing After Learning JUnit

Christian Shadis

CS-443 Self-Directed Blog Post #5

This past semester I have been spending a lot of time in my QA class working with JUnit 5. I want to be able to take my familiarity with JUnit and apply the same principles with unit testing in Python. I am leaning toward a data-centric career path and Python is widely used for data analytics, so this would be valuable information for me.

This post is not an expert-authored tutorial on Python unit testing because I, myself, am just getting started with it. In this post I will instead give tiny, bite-sized examples of just the basics, translating it from JUnit to Python unittest. I built identical, small classes in Java and Python, and will build tests to go with them. Below are the classes in Java and Python, respectively.

/**
 * Simple class with basic methods, written in Java
 * @author Christian Shadis
 */
public class main {
    public static void main(String[] args){
        int i = 0; // dummy code to keep compiler happy
    }

    public static int addTwoNumbers(int x, int y){
        return x + y;
    }

    public static String toCapital(String str){
        return str.toUpperCase();
    }
}

# Simple class with basic functions, written in Python
# Author: Christian Shadis

class main:
    def add_two_numbers(x, y):
        return x+y

    def to_capital(string):
        return string.upper()

Writing the unit tests in JUnit is simple: we import the JUnit assertions, and the @Test annotation. Then we create the test class, each of the two tests, setup, exercise, and verify just as always.

/**
 * Test Class for main.java
 * @author: Christian Shadis
 */
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class maintest {

    @Test
    void testAddTwoNumbers(){
        int result; // setup
        result = main.addTwoNumbers(566, 42); // exercise
        assertEquals(result, 608); // verify
    }

    @Test
    void testToCapital(){
        String result; // setup
        result = main.toCapital("string"); // exercise
        assertEquals(result, "STRING"); // verify
    }
}

Luckily, writing unit tests is just as easy in Python as Java. We import the unittest library and the other class, define the class, and add a Test Case object as the parameter.

import unittest
from main import *

class maintest(unittest.TestCase):
import unittest
from main import *

class maintest(unittest.TestCase):

    def test_add_two_numbers(self):

        pass
    def test_to_capital(self):

        pass

Now we need a test case for each of our two functions, add_two_numbers and to_capital. Python’s unittest objects have very similar assertions as in JUnit. Use assertEqual(x, y) to check that x == y. This is the assertion we will use in this example, but any of the following are commonly used unittest assertions:

  • assertEqual
  • assertNotEqual
  • assertTrue
  • assertFalse
  • assertIs
  • assertIsNot
  • assertIsNone
  • assertIsNotNone
  • assertIn
  • assertNotIn
  • assertIsInstance
  • assertIsNotInstance

assertEqual takes two arguments and, as the name suggests, asserts their equality. See the implementation below:

    def test_add_two_numbers(self):
        result = main.add_two_numbers(33, 44)
        self.assertEqual(result, 77)

    def test_to_capital(self):
        result = main.to_capital("hi")
        self.assertEqual(result, "HI")

Run the tests and you will see them both pass. Below is a screenshot of the tests executing in Python and then in JUnit. As you can see, the Python tests are slightly faster than the Java tests, but not by much. I used IntelliJ IDEA and Pycharm IDE.

I have found the most helpful way to learn testing is to just play around with the unit tests, see what works and what doesn’t, see what causes failures and what those failures look like, and so forth. I would suggest any other beginner QA student to do the same. Playing around with different assertions and looking at the unittest documentation is a great way to learn this library. I hope this post gave you some insight on how to get started with unit testing your Python modules if you have done some work with JUnit in the past.

4/28/2021

Works Cited:
Unittest – unit testing framework¶. (n.d.). Retrieved April 28, 2021, from https://docs.python.org/3/library/unittest.html

From the blog CS@Worcester – Christian Shadis' Blog by ctshadis and used with permission of the author. All other rights reserved by the author.

API Design with Java 8

In this blog post, Per-Åke Minborg talks about the fundamentals of good API design. His inspiration for writing this article is a blog post by Ference Mihaly which is essentially a check-list for good Java API design.

“API combines the best of two worlds, a firm and precise commitment combined with a high degree of implementation flexibility, eventually benefiting both the API designers and the API users.”

Do not Return Null to Indicate the Absence of a Value

Using the Optional class that was introduced in Java 8 can alleviate Javas problem with handling nulls. An example below shows the implementation of the Optional class.

Without Optional class

public String getComment() {

    return comment; // comment is nullable

}


With Optional class

public Optional getComment() {

    return Optional.ofNullable(comment);

}

Do not Use Arrays to Pass Values to and From the API

“In the general case, consider exposing a Stream, if the API is to return a collection of elements. This clearly states that the result is read-only (as opposed to a List which has a set() method).”

Not exposing a Stream

public String[] comments() {

    return comments; // Exposes the backing array!

}

Exposing a Stream

public Optional getComment() {

    return Optional.ofNullable(comment);

}

Consider Adding Static Interface Methods to Provide a Single Entry Point for Object Creation

Adding static interface methods allows the client code to create onjects that implement the interface. “For example, if we have an interface Point with two methods int x() and int y(), then we can expose a static method Point.of(int x, int y) that produces a (hidden) implementation of the interface.”

Not using static interface methods

Point point = new PointImpl(1,2);

Using static interface methods

Point point = Point.of(1,2);

I selected this resource because it relates to design principles, and it’s something that I do not know well. I would like to learn more about APIs and good practices for designing them using Java. The article had useful information and topics that I didn’t know well. A few more pointers from the article I learned:

  • Favor Composition With Functional Interfaces and Lambdas Over Inheritence – Avoid API inheritance, instead use static interface methods that take “one or several lambda parameters and apply those given lambdas to a default internal API implementation class.”
  • Ensure That You Add the @FunctionalInterface Annotation to Functional Interfaces – signals that API users may use lambdas to implement the interface
  • Avoid Overloading Methods With Functional Interfaces as Parameters – Can cause lambda ambiguity on the client side.

I would like to learn more about using AWS Lambdas, and learning more about APIs in general. I plan to use this information if I am ever to work on Java APIs which is possible. I want to make sure I have the best practices and the check list mentioned in the start of the article seems like a good starting point.

The post API Design with Java 8 appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

First Meet With Dhimitri

Jon, Dhimitri and I had a meeting today to catch Dhimitri up on what we have been doing and the plan for the next few months.  We met in the library and discussed how to set up Action Bar Sherlock and demo’d the app again.  We plan on following the style guide very thoroughly so the app will flow how normal Android apps work.  We also talked about trying the app done to a point where we could start field testing the app with students around campus and get a feel for what works and what will need improvement.

 

Everything seemed to go pretty well, I’ll be working on editing a task that has been previously made using ‘add task’ and I think I may just have the edit copy the old task and replace the new data instead of just updating, not too sure yet.

 

We talked about doing SQLite a little bit but the point still stands about leaving it out until later (if we want/need it).

From the blog jamescelona » WSU CS by jamescelona and used with permission of the author. All other rights reserved by the author.

Catching Up on GIT

Howdy all,

Luckily Jon and I have been working internships all summer using some sort of variation of a Version Control System.  I guess I didn’t learn as much as I thought in 401 for GIT as I really needed.  My git-foo has improved significantly (Jon’s is still way above mine, though. )  Right now I’m working on my james-dev branch (at least the one I push to) and usually branch when I’m trying something new.  I’m really digging the issue tracker but, I think one day this week I am going to take some time out, probably with Jon, and really get our Wiki in gear.

In other news, old news that I never mentioned, Joe was MIA for a while and I finally got in contact with him and he said he was too busy and couldn’t commit I emailed Karl about it but I never got a response, I’m sure he’s just enjoying summer.

From the blog jamescelona » WSU CS by jamescelona and used with permission of the author. All other rights reserved by the author.

Method chaining

While experimenting with adding context menus and alert dialogs to the app, I discovered a cool Java feature that I didn’t know existed: method chaining. By taking normally void methods and instead having them return a reference to their object, you can turn this:

Person p = new Person();
p.setName(“Bill”);
p.setAge(40);
p.setZip(01701);

into this:

Person p = new Person();
p.setName(“Bill”).setAge(40).setZip(01749);

As far as I can tell, efficiency doesn’t change when using method chaining vs. the traditional way. But it looks a lot cleaner and I may start using it.

From the blog Code Your Enthusiasm » WSU CS by Jon and used with permission of the author. All other rights reserved by the author.