Unit Testing: JUnit

Since for the second part of our “Software Quality Assur & Test” class, we are now beginning to test object-oriented software, I thought it would be useful for me to expand my knowledge of horizon on Junit. The article I read this week is about unit testing with JUnit 4 and JUnit5. It explains the creation of JUnit tests. It also covers the usage of the Eclipse IDE for developing software tests. In this blog I will be centered around JUnit 4 and the JUnit topics that I found useful for both my current software testing course and my professional career as well.

Define a test: To define that a certain method is a test method, annotate it with the @Test annotation. This method executes the code under test. Use an assert method, provided by JUnit to check an expected result versus the actual result.

Naming conventions: As a general rule, a test name should explain what the test does. If that is done correctly, reading the actual implementation can be avoided.

I will be naming my test methods as logically as I can, so that not only I know what exactly the test does, but also be easier for my team member to not to dig into the actual code, thereby saving the time, while working on group. Moreover, I will also avoid using testcase naming convention which uses class names and method names for testcases name.

Test execution order: JUnit assumes that all test methods can be executed in an arbitrary order. Well-written test code should not assume any order, i.e., tests should not depend on other tests.

Most of the times while writing my test cases, I used to think about the bigger picture. I used to scan through the entire project’s code, making sure that I know the relations and dependencies among the classes. This way, often, I ended up writing test cases that must be executed in a particular order. But now I will remember that tests should be independent, and test only one code unit at a time. I will try to make each test independent to all the others.

Defining test methods: JUnit uses annotations to mark methods as test methods and to configure them such as:

@Test, @Before, @After, @BeforeClass, @AfterClass, @Ignore , @Test (expected = Exception.class), @Test(timeout=100).

Assert statements: JUnit provides static methods to test for certain conditions via the Assertclass. These assert statements typically start with assert. They allow us to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value. It throws an AssertionException if the comparison fails. Most common methods include:

fail([message]), assertTrue([message,] boolean condition), assertFalse([message,] boolean condition), assertEquals([message,] expected, actual), assertNotEquals([message], expected, actual), assertNull([message], object-reference).

Form now onwards, while writing my asserts I will provide meaningful message in assert statements that will makes it easier later on to identify what exactly happened and fix the problem, if any error occurred.

For my next week I am looking forward in learning more about testing for exceptions and the use of assertThat statement.

Source: (http://www.vogella.com/tutorials/JUnit/article.html)

 

 

 

From the blog CS@Worcester – Not just another CS blog by osworup007 and used with permission of the author. All other rights reserved by the author.

10/16/2017 – blog Assignment Week 5 CS 443

http://reqtest.com/testing-blog/white-box-testing-example/
This week we generalize to whitebox testing. Whitebox testing or code based testing as the name implies works at the code based level. This technique does not rely on the specifications but instead provides the programmer with the actual code. Armed with such technical details, programmers can create test cases to test for the success of the system. The key principles to successful testing are the following:

Statement coverage – the simplest type of coverage ensures that every statement is executed.
Branch coverage which ensures that every branch is covered.
Finally, path coverage which ensures that all paths are tested.

Statement and branch coverage does not guarantee full edge coverage. So, above all path coverage is favoured for its comprehensiveness.
For code testing, I have always asked if white-box testing is enough to create a successful, working product when the tester already has the code. What are the advantages of black box testing when whitebox testing should be sufficient?
This article is all about whitebox testing. It poses the question of which is better white box or black box testing, but does to formulate any favoritism for either. Both has advantages/disadvantages depending on the scenario, so neither can be ruled out over the other. As stated in the article, black box testing allows the system to be tested from a user’s point of view. White box testing on the other hand allows the system to be tested from a developer’s point of view.
Black box testing allows the tester to have more perspective on the intended customer/users and tests for the expected results. For new insights, the author seems to favor it during the early stages of product development and the first few sprints in the release. It allows for further progress and development after eliminating “show stopper” bugs. However, from what I have seen black box testing is redundant and consumes too much time. One disadvantage is that test cases are extremely difficult to design when the specifications are unclear and not concise. One advantage is that it can test for boundary conditions.
White Box testing on the other hand, allows the tester to see the code. Therefore, it helps to bring out bugs that would otherwise be missed with black box testing. White box testing as stated helps to fix journeys and scenarios that would have otherwise been considered as exceptions, but that can be damaging in real life in terms of reputational, regulatory, and monetary damages. It allows for code optimizations by revealing hidden bugs. The emphasis on it is that it allows engineering teams to conduct thorough testing of the application by allowing for all possible paths to be covered. So, in my opinion whitebox testing should be given higher weights

I chose this article for generalization and out of interest to learn more about whitebox testing. Although the article does not show favoritism, I am in favor of most of the techniques over black box testing.

From the blog CS@Worcester – Site Title by myxuanonline and used with permission of the author. All other rights reserved by the author.

Blog 5: Control Statements Response

Hello fellow readers, today I read a blog post by the infocampusblog which is a software training institute. This blog focuses on control statements in Java and how they work in some cases.

The blog first touches on if statements and where you can go from there, mostly things that I learned in my CS-140 class but it was good to brush up on them again. Further into the blog, the writer touches upon For loops and how they are utilized in Java. Now For loops were another concept that I touched on in CS-140 but he goes in a little more depth explaining them than I remember learning back in the day. Then he talks about other loops like the do-while loop which is a very helpful one to use in Java to have your code continuously looped. Lastly the article touches upon remarks in Java such as Single Line comments, Multi Line comments and Documentation comments. I’ve done Single and Multi comments but I don’t think I have ever done Documentation comments.

The reason I choose this blog is because it is always nice to refresh your Java skills. I know I should always be coding even through the Summer just so I don’t forget certain coding techniques but I’m pretty lazy over the summer and sometimes over the school year I just come back to coding and I remember the concept but I don’t remember exactly how to do it. This blog post was great for that exact problem, I got to refresh myself on three different types of code. Now if-else statements and such, I remember those very well, those statements were stapled into my brain Freshman year in my CS-140 class and how they work. For loops, do-while loops and while loops are concepts like I was talking about where I remember them and kind of how to set them up but I need a little refresher to actually get it down and right so my code is the best it can be. Going to documentation, in my two years of coding, I don’t really use comments/remarks, I know I should because they help you not get lost in your code but I’m just lazy sometimes and don’t want to do it as it does take time. I will try to utilize all these methods in later Java programs as they are very helpful and can make my code better and regarding comments it can make my code easier to follow for people trying to read it and understand it. Thank you for reading my blog today, come back next week for some mode programming talk.

Source: https://infocamblog.wordpress.com/2017/10/10/java-programming-control-statements/

 

From the blog CS@Worcester – Benderson's Blog by bendersonsblog and used with permission of the author. All other rights reserved by the author.

Abstract Factories

http://www.oodesign.com/factory-pattern.html

http://www.oodesign.com/factory-method-pattern.html

http://www.oodesign.com/abstract-factory-pattern.html

Last week, on my blog, I discussed simple and static factories briefly.  That post, however; only talked about some of what factories can do.  This week, to round off my knowledge, I choose to reaffirm learn more about abstract factories.  The best resource I found to help me with the topic was oodesign.com (Object oriented design).  Above I’ve linked all three of their pages on factories but I’ll mostly be concerning myself with the last one, abstract factories.  For the most part, I can earnestly say I didn’t know much about abstract factories.  I’m not the most well-read developer, yet.  But immediately they seemed like an impressive tool.

From my readings and class lectures this week, I know that Factory Method pattern uses an interface to create objects while allowing for subclasses to decide the type of object.  I learned though, that abstract factories were an extension of this functionality.  They are essentially a factory of factories that allows us to take advantage of the “code to an interface” principle.

I can immediately recognize that abstract factories prove a good practice to code.  In the pages, I saw that every subclass had their own factory classes written for them (meaning that factory method pattern and abstract factories work well together).    Subclasses can be added to an interface, so long as they are compatible (in the same family of objects).  This would seem to promote easier refactoring and extending functionalities of programs.  And, as a developer, I assume that any program I write will need to be expanded or edited.  If abstract factories truly do make it easier on that front, then I’d be more than willing to use them.  Unfortunately, I do have a concern relating to their extendibility.

They aren’t entirely flexible, that is, an abstract factory can’t help creating in an object that isn’t in the same family.  The added abstraction and encapsulation seems like it would start to become overly complex or cluttered for it to be easily read by humans.  With every interface having multiple subclasses and factories, any UML diagram or visual would start to get cluttered or cumbersome if a program has multiple interfaces that create families of objects.  Making the code more efficient and organized doesn’t mean we’re making it easier to read.  We should remember that it’s humans that will edit our work after all. Though, since it seems like factories in general are prevalent, I’m sure I’ll become practiced enough that they aren’t daunting.  I just don’t want to be the guy who makes someone else’s day difficult because his code is hard to read.

Using abstract factories also avoids using conditional logic, it seems.  The usual factory design pattern would use if statements or switches to decide which subclass to return but, as I said before, each subclass has its own factory.  The abstract factory then returns the subclass depending on the input factory class.  Conditional statements aren’t necessarily difficult to write and understand.  The appeal to avoiding them, to me, is avoiding certain errors all together.  I have less to worry if less of my code can throw an error.  Also, if the program were of a larger size, there may be a so many conditions that writing a case or if statement for everyone would become painstaking.  Being able to avoid errors and making code easier to write is an attractive feature.

Just like the other factory patterns, I can see there is a place for abstract patterns in the workplace.  Now I just want to be sure I know when and how to use them.  I’ll certainly be practicing with them.

From the blog CS@Worcester – W.I.P. (Something catchy) by aguillardcsblog and used with permission of the author. All other rights reserved by the author.

The Limits of Automated Testing

Automated testing is great, and it isn’t going anywhere. The ability to find bugs in a program with minimal human intervention saves both time and money, as well as helps to make the program more reliable. The problem with automated testing is that the automation can not think like a human. The automated tests simply follow the algorithm that they were programmed to follow. This may be great for finding simple bugs or obvious faults, but may be insufficient for revealing complex or hidden bugs.

On the September 10, 2017 episode of Test Talks, Jean Ann Harrison argues that what we need in order to find these complex, hidden bugs, is critical thinking. As an experienced tester who has worked in the industry for nearly 20 years as everything from a mobile tester to a quality assurance auditor, Harrison knows a fair deal about finding bugs in software. As a medical device tester, Jean Ann states that she often considered not was the product was designed to do, but what it was capable of. When it is a matter of life or death, there is no room for crippling bugs to make it into the final product.

I think that Harrison took many of her experiences as a medical device tester into her current position as a quality assurance auditor of airline entertainment software. In addition to the strict FAA requirements that she must adhere to, once again there are lives at risk if there are bugs that go unnoticed and unaddressed. When considering possible scenarios to test the product under, Harrison repeatedly states that she uses critical thinking skills to think outside of the box; she is always asking herself “what if…?” She states that asking these sorts of questions, along with imagining the possible scenarios in which the product would be used, will lead to the development of meaning tests and possibly reveal bugs.

Strictly following the testing methods that I’ve learned as a Software QA & Testing student so far seems to keep me inside a bubble. I am only able to test what the method states should be tested. This is sometimes difficult because my mind has a tendency to think of all of the possibilities, much like what Harrison is advocating for testers to do. I want to stray from the strictly defined values that the method demands I input and attempt to use my experience as an end-user and also my experience as a programmer to attempt to break the program. Of course, in the context of testing, breaking a program is a success. It means that you have found a bug and that the finished product will be that much better. I look forward to applying Harrison’s critical thinking strategy to my testing in the future. I am excited to investigate “what if…?” and hopefully make programs better by discovering bugs that would have otherwise gone unchecked.

From the blog CS@Worcester – ~/GeorgeMatthew/etc by gmatthew and used with permission of the author. All other rights reserved by the author.

The Place For Tools in Testing

Especially for new or inexperienced programmers, tools can be a great way to help get the ball rolling or learn how to create programs that work. Too often, however, programmers rely on their tools to think for them, a dangerous and often damaging decision. A post by Robert Martin on his Clean Coder Blog titled “Tools are not the Answer,” explains potential causes of the impending “software apocalypse” and also points out some common mistakes that developers should avoid. Martin acknowledges the value of tools and technologies such as Light Table, but feels that such tools are not going to solve the apocalypse. Tools only further complicate things rather than addressing the underlying cause, which Martin cites as software programmers being generally undisciplined.

Rather than trying to fix bad code with more code, Martin thinks that we should simply aim for more disciplined programming. The reasons he gives for the cause of the apocalypse are:

  1. Too many programmer take sloppy short-cuts under schedule pressure.
  2. Too many other programmers think it’s fine, and provide cover.

I feel that Martin’s first reason is more significant than the second. While often times deadlines are outside of the programmer’s control, the choice to take a short-cut that jeopardizes the integrity of the code is a conscious choice. Avoiding this dangerous mistake may require extending deadlines or missing them altogether. Weighing the risks of releasing an inferior product with delivering it past its original deadline may depend on the product’s application. Reputations would certainly be more severely impacted by the former, while the latter may cause only minor inconvenience to the end-user.

I don’t see the second reason Martin states as so much of a problem. I would argue that other, more experienced programmers should help to implement the feature properly rather than allowing an overwhelmed programmer to sloppily stumble through a buggy implementation. Martin seems to think that tattling on the sloppy programmer is the solution to making sure that he pays for his carelessness. I think that in any team-driven environment, colleagues should have one another’s backs and everyone should be accountable.

While I stand behind Martin’s opinion that the real reason behind the impending software apocalypse is a lack of general discipline among programmers, I only partly agree with the causes he proposes for this lack of discipline. I think that more importantly than anything else, the programmer must consider the risk he or she is taking by rushing through something without proper and rigorous testing. Some of the examples of software bugs that caused panic and chaos are found in “The Coming Software Apocalypse,” which is the article that Martin continuously refers to in his own blog post. While the code that I am presently writing does not have any real-world consequences (apart from a poor grade if it does not meet the requirements of the assignment), I am challenging myself to write code as if someone’s life depended on the reliability of what I write. Who knows, someday it just might.

From the blog CS@Worcester – ~/GeorgeMatthew/etc by gmatthew and used with permission of the author. All other rights reserved by the author.

B5: Encapsulation

Encapsulation

        I chose a podcast this week to try and broaden my learning experience using different resources. This podcast talked about object oriented programming dealing specifically with the idea of encapsulation. It went through the basics of what encapsulation is and how classes, methods, and variables all connect with each other to hide data. The people on the podcast explained the differences that encapsulation can have between different languages but the basic idea is essentially the same. The overall syntax may change slightly but the idea of data and code being hidden from the user is still there. They then explain how the idea of a roadmap works well with this idea and how helpful it could be if other programmers are looking at the code. It allows programmers to understand what they can and should use in your code. They go over access modifies such as public, private, and protected where they explain that giving the user all the code can be harmful as that allows the user to change values that could end up breaking the program. They also use global variables to help show this point by saying they are not reusable and make it more difficult to track down errors.

         I chose this podcast because encapsulation is an essential part of coding in an object-oriented language like java. It allows the programmer to hide code that doesn’t need to be seen by the user to make sure that they can’t alter anything they shouldn’t. I have to admit that out of all the complicated podcasts I searched through, this one especially made it easy to understand java concepts. Coding blocks has a solid source of information and does a great job explaining how everything works using their own definitions for the somewhat confusing vocabulary. Although I already knew most of this information, it was a great idea to refresh on it because I had forgot all the vocab such as mutators and accessor methods which I just called getters and setters. Overall the content was very easy to understand due to the helpful explanations given by the people in the podcast. It affected and helped me by allowing me to refresh on encapsulation and encouraged me to go look at inheritance along with polymorphism again. This obviously will tie back to our class since we’re going to be using a lot of object oriented programming in java and using encapsulation to work on our projects. Encapsulation will have a big impact on my practice of code as it will help shape my design for how the code will look and what the user will have access to if I want them to only have limited control over the program.

From the blog CS@Worcester – Student To Scholar by kumarcomputerscience and used with permission of the author. All other rights reserved by the author.

Design Patterns: Favorites

URL:https://www.codingblocks.net/podcast/design-patterns-iterators-observers-and-chains-oh-my/
I know it may be a little redundant, but again like the past two weeks, my blogpost for this week will be about Design Patterns, but it will part three of four of the Coding Blocks Design Patterns Saga. This time though, the podcast did not focus on a specific kind of Design Pattern, but instead their favorites. In this week’s blog I will be explaining what was discussed on the podcast in detail, examples that go along with it and what I had learned from it. The three Design Patterns summarized today are Observer Pattern, Chain of Responsibility, and Iterators.     So, Observer Patterns maintains its dependences by notifying them of events by calling a method on the dependent. So in a nutshell when an object, which is called a subject in this case, maintains a list of its dependents and notifies them automatically of any state changes usually by calling one of their methods. The downside of this is that it can cause memory leaks. The class that is adding these response headers to this element has got a strong hold of these objects. If they are never disposed of or the garbage collector never gets them properly, all these objects just stay alive and never get taken away. An example is a notification example on your phone. It doesn’t care what someone else’s phone does with notifications. Notifications are sent from the server to my phone that I am subscribed to and I am notified of events in some way. I don’t care what happens on other people’s phones, but I respond in a certain. Visualize a pubsub environment, each responder of each element can happen independently from the other and it doesn’t matter how they respond. The other downside is the abstraction layer hopping. It is pretty much when the layers in between are ignored and shortcutting the system.      The second Design Pattern was Chain of responsibilities and there is no strong use case. So to start off with an example, you are part of a large company. THis company had a purchasing request. If the request was under $50, it is approved. If it is greater than $50 but under $250 the manager has to sign it off. If it is greater than $250 but under $500 the accountant takes care of it and if it is under $5000 but greater than $500 the CEO decides. So while this is a bad example of inheritance, you inherit from manager, manager inherits from accountant, and accountant inherits from CEO, so it is still inheritance. So you say if it’s greater than 50, pass to next part, and greater than 250, pass it up until you get to the designated area. What I thought was really interesting though, was when they mentioned a real world example which is exception handling.      The last one mentioned today was Iterators, which I had heard of before this. Iterators are a pattern in which the iterator is used to traverse a container and access the container’s elements but the pattern decouples the algorithms from the container. So algorithms are container specific and cannot be decoupled. It provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation and not exposing what that data is. A good example is the fibonacci sequence, since it technically does not have to do with any lists or arrays. When you want to sequentially traverse whatever that collection might be and you want to decouple that traversal algorithm away from the container, you don’t want the user to know how you’re containing that data. You still want the user to be allowed to traverse through the data. The consequence of this is that sequentially has to keep track of its location, and can have two loops accessing the same iterator.      The last thing mentioned in the podcast as usual was its resources which as always I love. It just gives me more resources that I cn had to my little library and will help me a lot in the future. Now honestly, this podcast was not as interesting as the first two for me. With the first two, I was learning about them in class, so it was cool to compare and contrast was was said on the podcast to what I was learning in my class. With these three Design Patterns, I hadn’t ever really hear of them, except iterators, and they just were a little hard to completely understand without a visual representation. I think like the other two though, knowing these Design Patterns in general will help me with my future coding and that is what is more important. 

From the blog mrogers4836 by mrogers4836 and used with permission of the author. All other rights reserved by the author.

Lesser–Known Java Syntaxes

https://blog.joegreen.pl/lesser-known-java-syntaxes.html

Today I stumbled across an interesting little blog post on lesser-known Java syntax. The author gives examples of code that doesn’t look like it would compile, but is surprisingly still legal syntax. For example, a two-dimensional array is usually declared like this:

int[][] arrayOfIntArrays;

However, since the brackets can be placed after either the type or identifier when declaring a regular array:

int[] intArray;
int intArray[];

A two-dimensional array can also be declared like this:

int[] arrayOfIntArrays[];

An interesting (although hard to read) application of this is that a single and multidimensional array can be declared on the same line:

int[] intArray, arrayOfIntArrays[];

This line of code declares an array intArray and a two-dimensional array arrayOfIntArrays. The second one is two-dimensional because the brackets are placed after both the type and identifier just like the previous example. The fact that another array is declared on the same line does not change anything. Although it is not very practical, it is still a very interesting use of syntax that compiles just fine. Similar syntax can be used when specifying the return type of a method. A method that returns a two-dimensional array would usually look like this:

int[][] fun();

But since brackets can be added to the end of the method signature, it can also look like this:

int[] fun()[];

Taking all of this to the extreme, a method that takes an array of arrays as a parameter and returns an array of arrays can be written like this:

int[] fun(int[] arrayOfIntArrays[])[];

Next the blog discusses the receiver parameter, which is a syntactic device for an instance method or inner class’s constructor.

class MyClass {
    public void method(MyClass this, int argument) {
    }
}

This code compiles and generates the same bytecode without MyClass this as a parameter. Currently the only use of this syntax is to annotate the argument.

The most commonly taught way to initialize an array is like this:

int[] intArray = new int[]{1, 2, 3}; 

However, the type of the array does not have to be specified twice. Instead, an array can be declared like this:

int[] intArray = {1, 2, 3};

But splitting this line of code into two lines will not compile. If the array is declared without being initialized, the new int[] must be included when the array is initialized.

I selected this blog post because I think it is very interesting and useful to see examples of code that don’t look like they should compile, but they do because there is nothing wrong with the syntax. It’s important for a software developer to know the ins and outs of the language they are developing in and knowing little quirks like this helps give a better overall understanding of the language. The more syntax you know the less caught off guard you will be when reading other people’s code, as nobody uses the exact same syntax in every situation.

I learned specific syntax from this blog that I will now understand if I ever see. These examples helped me better understand Java syntax in general, which will make it easier to read other people’s code and will make me less prone to errors.

 

From the blog CS@Worcester – Computer Science Blog by rydercsblog and used with permission of the author. All other rights reserved by the author.

Quality Assurance – The Most Important Aspect of Testing

A big part of testing is making sure that the product you are working on is going to be a highly reliable, quality piece of software. Quality assurance is a big part of testing as a poorly designed product could mean bad news later on down the line. Softwaretestinghelp.com recently posted a blog that dives into this subject.

The first thing that stood out to me in the blog was a formula: Quality assurance = quality control + defect prevention. This formal makes a lot of sense to be. One of the main goals of testing is making sure it works as it should and if it doesn’t making sure someone knows it needs to be fixed. That is the quality control portion of the equation. The second part, defect prevention, is preventing bugs from getting into the software in the first place or recognizing a problem before it happens. I feel if you complete testing with confidence that those two items have been completed, you have done your job as a tester.

Now, how might one go about making sure they hit the mark with the formula? First of all, reviews are a very important aspect. This includes design reviews, specification reviews, code reviews, etc. I cannot express the importance of reviews. Getting other sets of eyes on things are crucial to making sure nothing is missed. From my experience at work, reviews are done for anything and everything, and if a review isn’t done it usually sent out with a disclaimer that whatever is being sent out is a draft. It will bite you if you don’t. Another important step to meeting the requirements of the formula is logging any issues that may have been find when testing. Any issue, not matter how small, should be logged and investigated to determine the problem and if any action is needed. This relates to the next item of the list, which is finding the root of the problem. Often a bunch of little issues that have to keep being fended off are really due to some underlying issue. It is important to make sure that you find the real issue, and not just cover it up. Lastly, make sure as a tester you utilize the resources you have available to you, especially your manager. They have the ability to get you what you need and probably know that quickest way to get it. Most of the time they are more than willing to help as your work reflects on them as well.

This blog provided a nice intro into testing with quality assurance in mind.  I found their thoughts to be intriguing and will be on the lookout for more blogs like this one considering how important quality assurance is to a piece of software.

Link:

http://www.softwaretestinghelp.com/defect-prevention-methods/

From the blog CS@Worcester – README by Matthew Foley and used with permission of the author. All other rights reserved by the author.