ComputerScienceExpert

(11)

$18/per page/

About ComputerScienceExpert

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Applied Sciences,Calculus See all
Applied Sciences,Calculus,Chemistry,Computer Science,Environmental science,Information Systems,Science Hide all
Teaching Since: Apr 2017
Last Sign in: 103 Weeks Ago, 2 Days Ago
Questions Answered: 4870
Tutorials Posted: 4863

Education

  • MBA IT, Mater in Science and Technology
    Devry
    Jul-1996 - Jul-2000

Experience

  • Professor
    Devry University
    Mar-2010 - Oct-2016

Category > Programming Posted 06 Jun 2017 My Price 9.00

public void testOuterHandle

Hello, I see that rajput84 has answered this before. I signed up to 'unlock' the result but I cannot find them anywhere. I need assistance solving this.

 

Minivan Doors

Learning objectives

Write a class with multiple methods and a constructor

Write instance variable (field) declarations

Write accessor and mutator methods

Use if statements and boolean conditions

Use an enumeration type

Use a Java ArrayList

Write a JUnit test class

Overview

In this assignment, you will write another complete class that is intended to reinforce your skills in writing instance variables, accessors, and mutator methods, while also increasing the use of if statements to provide conditional logic. You will continue writing unit tests for your work using the JUnit testing framework. But you will write tests that cover all of your code, rather than just the methods.

Your task is to simulate a portion of the control software for a minivan with a powered sliding door. You will write a class that represents the state of the controls, providing accessor method for the state of the van, and mutator methods that allow you to change that state.

Details

The minivan that we are modeling has a power sliding door. The door can be locked or unlocked using a dashboard button. The door can be opened by either a dashboard button, its inside handle, or its outside handle. However, the inside handles do not work if the minivan's child lock switch is activated. In order for the sliding door to open, the door must be unlocked and the gear shift must be in park. You will write a class that represents these vehicle features, and models the process of deciding whether a sliding door will open or not.

In addition to this, you will implement a log of responses to all attempts to change the state of the minivan (door, gear, child-safety-lock). The responses (which are strings) should be stored in a Java ArrayList. A file with all possible responses is given to you, so you should not try to come up with your own "custom" responses. You will also write software tests to confirm your solution works the way it should.

Setting Up Your Eclipse Project

Create a new Java project, and in the src folder of that project create a package named "minivan". The package name must be in all lowercase letters. Create a new class in the default package calledMinivan and use the starter code below for its initial contents (you'll have to fill in the comments yourself):

package minivan;

/**

 *  Write a one-sentence summary of your class here.

 *  Follow it with additional details about its purpose, what abstraction

 *  it represents, and how to use it.

 *

 *  @author your name (your-pid)

 *  @version (place the date here, in this format: yyyy.mm.dd)

 */

public class Minivan {

    //~ Fields ................................................................

    //~ Constructor ...........................................................

    /**

     * Creates a new minivan object with the doors closed,

     * gear shift in park, child lock switch off, and master unlock

     * switch on (unlocked).

     */

    public Minivan()

    {

        /* Insert your own constructor code here */

    }

    //~Public  Methods ........................................................

    /**

     * Replace this with your own comment.

     */

    public void pullOuterHandle()

    {

        // Just a "stub"--a dummy implementation that is just

        // enough for the compiler to compile the class. Just

        // serves as a placeholder for the real thing, to come later.

        return false;

    }

}

This is the start of your Minivan class, and already has one method stubbed out--which means there is a very minimal do-nothing implementation of the method, which is just enough to get the method to compile. You'll see why in a minute.

Create the test class by right-clicking on Minivan.java class and choosing New -> JUnit Test Case. By default, this will create a class called MinivanTest and ask you if you want to load JUnit. Make sure you choose to load JUnit 4 rather than JUnit 3. Use the text below for its initial contents (you'll have to fill in the comments yourself).

package minivan;

/**

 *  Write a one-sentence summary of your test class here.

 *  Summarize what your test objectives are.

 *

 *  @author your name (your-pid)

 *  @version (place the date here, in this format: yyyy.mm.dd)

 */

public class MinivanTest

    extends student.TestCase

{

    //~ Fields ................................................................

    // Holds a minivan object to be used in your individual tests

    private Minivan minivan;

    //~ Constructor ...........................................................

    /**

     * Creates a new MinivanTest test object.

     */

    public MinivanTest()

    {

        // The constructor is usually empty in unit tests, since it runs

        // once for the whole class, not once for each test method.

        // Per-test initialization should be placed in setUp() instead.

    }

    //~ Methods ...............................................................

    /**

     * Sets up the test fixture.

     * Called before every test case method.

     * Here, we just create a minivan using the default constructor,

     * so a freshly created minivan is available for use in each test.

     */

    public void setUp()

    {

        minivan = new Minivan();

    }

    /**

     * Check that the outside handle opens the door in

     * a newly constructed minivan object and that the log

     * message is the one we expect.

     */

    public void testOuterHandleWithDefaultMinivan()

    {

        minivan.pullOuterHandle();

        assertTrue(minivan.isOpen());

        assertEquals(Message.DOOR_NOW_OPEN, minivan.getLastMessage());

    }

}

Before You Start: Unit Testing in this Assignment

In this assignment, you will writesoftware tests for your work so that you can self-check your code as you write it. Self-checking is an important way for your to confirm your code works the way you expect, and it is really helpful at allowing you to find your own errors as you work.

Sometimes, students with more experience programming aren't too excited about writing software tests, which is understandable. They can seem a bit boring. However, if you remember back to your math classes or writing classes during your earlier education, you probably recall at least some time you spent checking your own work. In math, when you solve an equation, it is a really good idea to plug the answer you came up with back into the original equation to see if it works. That's a really strong way to double-check your work to make sure that simple mechanical mistakes (like accidentally flipping a sign, or other small errors) get found right away. Similarly, when writing you're probably used to repeatedly proof-reading your own words--that is a useful self-checking technique, but it isn't quite as reliable as "plugging the answer back into the original", because there's no definitive way to tell if your proof-reading found all the problems. Still, you do it because it helps improve the quality of your work.

So, software testing the way we're going to practice it in this class amounts to the same thing: it is your way of self-checking your own work to find mistakes. Further, if you self-check each piece of your codeas you write it you'll find more errors faster. If you write all your code first, and save all the self-checking for the end, your self-checking won't find as many errors. Worse still, when you find a problem, you may not know exactly where in your assignment the problem is, and it can take a lot longer to locate the cause of the mistake and fix it. Generally speaking, if you test your own code as you write it, you'll find more errors faster, and save more time later compared to saving software testing (i.e., self-checking) until the end after your entire assignment is complete. So please write software tests for each method, as you write that method rather than saving testing for the end.

OK, with that out of the way, you need to know how to write software tests. Software tests work best when they are short and focused--focus on testing one single thing at a time. We'll be writing our software tests as individual methods. Each test (each method) will have a very simple structure with three main steps, like this:

    public void testSomething()

    {

        // 1. Set up initial conditions for your test

        // 2. Perform the action you want to test

        // 3. Check that it behaved as you expected

    }

For example, the initial contents shown above for the Minivan class include a stub for a method called pullOuterHandle() that represents pulling on the outside door handle of the sliding door on the minivan. This action might open the door, and the minivan accessor method isOpen() will return true if it does, or false if the door stays closed. Suppose we want to test this method in a newly constructed minivan. We could do this as follows:

Create a new minivan. The door of a new minivan is closed and unlocked by default. It's child safety lock is off, and its gear is set to PARK.

Pull the outer door handle.

Check that the door really did open.

In code, it might look like this:

 

    @Test

    public void testOuterHandleWithDefaultMinivan()

    {

        // 1. Set up initial conditions for your test

        Minivan minivan = new Minivan();

        // 2. Perform the action you want to test (often using mutators)

        minivan.pullLeftOuterHandle();

        // 3. Check that it behaved as you expected (often using accessors)

        assertTrue(minivan.isOpen());

    }

Note that this method has a name that starts with "test". This is a convention, but it also allows JUnit to recognize your test methods easily. If you don't want to use names that start with "test", you can instead use the @Test annotation as shown in the textbook.

The first step in the test method shown above, which involves setting things up in the situation you want to test, is just plain old Java. Just create the objects you need, and call whatever methods are necessary to put them in the state you want them in for your test.

Note that setting up the "starting state" for tests is such a common thing, there's also a shorthand. In the provided text for the MinivanTest class above, you'll see the class actually declares a field calledminivan instead of using a local variable. It also provides a method called setUp() that initializes the field. These two go together to perform step (1) for many of your tests. JUnit will automatically invoke the setUp() method (if you have one) before every single test is executed. That makes it a great place to put common initialization actions you want to happen before each and every test--and a great place to put code for step (1), so you don't have to repeat that code in every single test method. That's why the version of the test provided earlier doesn't even include a step (1)--that step was placed insetUp() instead.

The second step involves calling the action you want to check. It's pretty easy, since it is usually just a method call. In fact, it is so short that often times it might even be combined with step (3). However, for every test, it should be clear to you that there is one specific method call inside the test that is the "thing being tested".

The third step is to check your work! That is, check that the method you're testing did what it is supposed to do. In some cases, the method may simply return a result. In that case, all you have to do is make sure the correct result is returned. In other cases, the method might change the object you're working with. Then you'd need to call one (or more) accessors to check that the object changed appropriately.

In either case, the tool you'll use to check that something happened the way you expected are assert methods. These are utility methods provided by JUnit just for the purpose of checking results, and they typically have names that start with "assert". The three you might use in this assignment are:

Method

Meaning

assertEquals(expected, actual);

Assert that two values are equal, using the equals(Object) method to compare them. This is the most commonly used assert method in your arsenal.

assertTrue(condition);

Assert that a boolean condition is true.

assertFalse(condition);

Assert that a boolean condition is false.

Note that if there are two parameters, the expected value always comes first and the value you are checking always comes second.

To run your tests, right-click on your MinivanTest class in the package explorer view and choose Run As -> JUnit Test.

Eclipse will run all your tests and show you the results. Here, we expect our first test to fail, since we haven't implemented anything yet and just have a stub. Eclipse will show your JUnit results in a graphical view where a green bar means that all your tests passed and a red bar means that at least one of your tests failed.

OK, so now you have a Minivan class ready, and a MinivanTest class that's also ready. Our advice for this assignment is to do the following:

Read through the requirements for the Minivan class so that you understand what it is supposed to do.

Plan the order in which you want to implement the minivan's methods. If your class has simple getter methods - as Minivan does - it is best to implement these first, especially if they are so simple that they just return the value of one of your fields. Simple accessor methods are often used in unit tests to check whether a mutator method changed the state of the object appropriately.

Implement methods one at a time according to your plan. Feel free to adjust your plan as you need to. However, focus on writing one method at a time.

Test each method as you write it. Write your tests as you write each individual method. Some students find it useful to write a stub of their method first so they can write their tests before they actually do the implementation. The stub allows your tests to compile, even though initially they'll all fail. This strategy goes by the name of test-first coding.

The Requirements for the Minivan

Write a class called Minivan that models the door-opening behavior of our minivan. Recall that to open the Minivan door, the door must be unlocked, and the van must be in park. If you are using the inside handle to open the door, the child safety lock must be off. Your class should provide the following methods (you define the instance variables/fields you need):

Minivan()

This default constructor initializes the minivan so that the door is open and unlocked, the child lock switch is off, and the gear shift is in park. The log will have nothing in it.

isOpen()

A boolean accessor method that returns true if the minivan door is open and false if the minivan door is closed.

isLocked()

A boolean accessor method that returns true if the minivan door is locked and false if the minivan door is unlocked.

getChildLock()

A boolean accessor method that returns true if the child lock is on (activated) and false if the child lock is off.

getGear()

An accessor method that returns the Gear that the minivan is in. Gear is an Enumeration type that is provided for you. An enumeration type is a special kind of Java class that is made up of a finite number of constants. You access these constants by calling them with the class name (ex. Gear.PARK)

pushLockButton()

A mutator method that locks the door. Even if the doors are open they can still be locked.

pushUnlockButton()

A mutator method that unlocks the door.

setChildLock(boolean value)

A mutator method that turns on the child safety lock (if value is true) or turns off the child safety lock (if value is false).

pullInsideHandle()

A mutator method that simulates opening (or attempting to open) the door using the inside handle.

pullOutsideHandle()

A mutator method that simulates opening (or attempting to open) the door using the outside handle.

pushOpenButton()

A mutator method that simulates opening (or attempting to open) the door using the dashboard button.

closeDoor()

A mutator method that simulates closing the door.

setGear(Gear gearArg)

A mutator method that sets that gear to one of the constants in the Gear enumeration type.

printLog()

An accessor method that prints the entire log, with each method on a separate line.

printLastMessage()

An accessor method that returns the last message in the log. This one is very usefult for unit tests.

toString()

The string representation of the minivan. A newly created minivan has a three line string output:

The van is in PARK.

The child lock is off.

The door is closed and unlocked.

The Minivan Log

To implement the minivan log, create a field in your class named log that is of type List and takes a String type as its type parameter. We will learn more about type parameters when we talk about generics, but in most cases, they simply restrict what types of objects you put into your data structure. In this case, we want a list of strings. Here is how you declare that:

List<String> log;

Inside the constructor, initialize your log to be a new, empty ArrayList. Here is how to do that:

log = new ArrayList<>();

Adding something to the end of a list is easy:

log.add(Message.DOOR_NOW_OPEN);

And iterating though the contents of a list is also simple:

for (String entry : log) {

    System.out.println(entry);

}

The minivan log will record every single attempt to change the state of the minivan. Essentially, that means it will add one message to the log every time you call a mutator method. There are three broad categories of messages.

A method requests that some state be modified but the configuration of the minivan prevents it. For example, trying to open the door when the door is locked. It logs the message: Message.DOOR_LOCKED

A method requests a state change but the minivan is already in that state. For example, trying to open the door when the door is already open. It logs the message: Message.DOOR_ALREADY_OPEN

A method requests a state change that succeeds. For example, you try to open a closed door an are successful. It logs the message: Message.DOOR_NOW_OPEN

Code for Gear Enumeration Type

package minivan;

public enum Gear {

    PARK,

    REVERSE,

    NEUTRAL,

    FIRST,

    SECOND,

    THIRD,

    DRIVE

}

Code for Message class

package minivan;

public class Message {

 

    public static final String DOOR_NOW_OPEN = "The door is now open.";

    public static final String DOOR_NOW_CLOSED = "The door is now closed";

    public static final String DOOR_NOW_LOCKED = "The door is now locked";

    public static final String DOOR_NOW_UNLOCKED = "The door is now unlocked.";

    public static final String CHILD_LOCK_NOW_ON = "The child lock is now on.";

    public static final String CHILD_LOCK_NOW_OFF = "The child lock is now off.";

    public static final String DOOR_ALREADY_OPEN = "The door is already open.";

    public static final String DOOR_ALREADY_CLOSED = "The door is already closed";

    public static final String DOOR_ALREADY_LOCKED = "The door is already locked";

    public static final String DOOR_ALREADY_UNLOCKED = "The door is already unlocked.";

    public static final String CHILD_LOCK_ALREADY_ON = "The child lock is already on.";

    public static final String CHILD_LOCK_ALREADY_OFF = "The child lock is already off.";

 

    public static final String DOOR_LOCKED = "The door is locked.";

    public static final String NOT_IN_PARK = "The van is not in park.";

    public static final String CHILD_LOCK_ON = "The child lock is on.";   

 

    public static String nowGear(Gear gear) {

        return "The van is now in " + gear + ".";

    }

 

    public static String alreadyGear(Gear gear) {

        return "The van is already in " + gear + ".";       

    }

}

A Word about Design

For this assignment, you'll notice that there are some features that are repeated (perhaps with minor variations) in the Minivan class. If you review the program grading rubric for this course, you will notice that "repeated code" is one of a number of design weaknesses that can cause your solution to receive lower ratings. When you discover these sections of repeated code, consider creating your own "helper" method(s) so that you can write such code once, and simply call it in multiple places instead of repeating it.

Also, as you test your code, you may find that the autograder indicates you have logical conditions (if statements) that are not being thoroughly tested. When you have multiple conditions combined with && or||, make sure you include separate tests for each unique way the condition can succeed or fail. For example, if you have an if statement that includes a condition like (isHappy || !isBusy) remember that there are 3 separate ways the condition can be determined. First, if isHappy is true, the condition will also be true. However, if isHappy is false, there are two more possibilities (either isBusy is true, orisBusy is false). You'll need to test all three possibilities for an if statement with this kind of condition in order to get full credit. In general, if there are K basic conditions or comparisons in an if statement, then there are K + 1 test cases needed to cover all the possibilities (in this example, 2 basic conditions means 3 separate test situations). 

Answers

(11)
Status NEW Posted 06 Jun 2017 08:06 AM My Price 9.00

-----------

Not Rated(0)