Junit testing a class which extends WizardPage - java

I am tasked with trying to create a Junit test suite of a class which extends 'WizardPage'.
public class PageDataModel extends WizardPage
Every time I try and create an object of this class within my test suit, the value of the page is null.
Below is an example of a test I'm trying to execute.
#Test
public void testEntityName() {
PageDataModel pageDataModel = new PageDataModel("testing");
pageDataModel.setContents("person");
String temp = pageDataModel.getContents();
assertEquals("person",temp );
}
Could someone please suggest where I'm going wrong. Many thanks.

If you are talking about org.eclipse.jface.wizard.WizardPage, you need to check your setContents() and getContents() methods (as far as I remember, WizardPage does not provide that method to you).
Do you store the String you pass in setContents() anywhere? Do you return that content in getContents()?

Related

How to have multiple setups for different sets of JUnit Tests?

I have just started learning JUnit very recently and came across the following problem.
Have a look at the following class
class MyClass {
String a;
public MyClass(String a) {
this.a=a;
String doSomething(String a) {
if( a.isEmpty() )
return "isEmpty";
else
return"isNotEmpty";
}
I want to test the above method for both the conditions. If I proceed with the general structure of writing testcases it will look something like this:
class MyClassTest {
MyClass myClass;
#BeforeEach
void setUp() {
myClass=new MyClass("sampleString");
}
#Test
void doSomethingTest() {
Assertions.equal("isNotEmpty", myClass.doSomething());
}
}
However, for testing the empty string condition I will need another setup method where instead of "sampleString" I pass an empty string.
Following are the approaches I could think of and the questions for each:
Not use setUp at all and instead initialize the class in the individual test method. However, if let's say there are 10 testcases; 5 of which require empty string and rest "sampleString" then this doesn't make sense. Again, we can have a separate method for this repetitive code and call it individually in each testcase but then that defeats the purpose of having a steup method. Lets say I wanted to use two different setup methods, is there a way to do so?
Have a parameterized setup. I don't know if this is possible though. If yes, please share some useful links for this.
Use TestFactory. I tried reading up about this, but couldn't find an example for this specific case. If you have any, please share.
This example has been kept simple for illustrative purposes.
Group the tests with the same setup in an inner class annotated with #Nested. Each nested test class can have its own setup in a local #BeforeEach method.
You can always prepare the non-common data inside your test method. I've always thought it's easier this way, compared to using parameterized tests. You can't mix parameterized and non-parameterized tests in 1 file.
#Test
void doSomething_nullString()
{
myClass = new MyClass(null);
Assert.assertNull(myClass.doSomething());
}
#Test
void doSomething_emptyString()
{
myClass = new MyClass("");
Assert.assertEquals("", myClass.doSomething());
}
#Test
void doSomething_nonEmptyString()
{
myClass = new MyClass("sampleString");
Assert.assertEquals("sampleString", myClass.doSomething());
}
Or, you can always have helper methods inside the test class.
private MyClass createTestObject_nonNullString() {
return new MyClass("nonNullString");
}
private MyClass createTestObject_nullString() {
return new MyClass(null);
}
#Test
public void doSomething_sample() {
MyClass test = createTestObject_nonNullString();
// perform test
}

Access private method of an instance in unit test

I came across the following issue when I was trying to unit test my code. If I have a class that creates an instance and for example a getter method like this:
public class Test {
private static Test instance;
private ArrayList<String> arrayList = new ArrayList<String>();
public static Test getInstance() {
return instance;
}
private ArrayList<String> getArrayList() {
return arrayList;
}
}
If now I want to access the arrayList in a test case it would fail, because the list is returned by a non-accessable private method. So trying something like this wouldn't work:
public class AccessTest {
private Test test;
public void accessList(){
test = Test.getInstance();
test.getArrayList();
}
}
So one way to access the arrayList anyway, would probably be to change the visibility to protected. But isn't there a better way to access the method? Is it really necessary to make a method protected only because of a test that needs to access it?
In general, if you have some private methods in your class and you feel that you have problems with testing them, it is a sign of a bit of a code smell. It shows that too many functionality is hidden behind private wall.
You could change visibility of such method to package protected, so JUnit test will see it. There is also a Google Guava annotation #VisibleForTesting or something like that. But again - this is a sign of wrong class design.
Think of extracting such method to a separate class and make that methods public then.
For example, take a look at the following code:
class ReportCreator {
public File createSomeImportantReport(LocalDate date) {
String fileName = provideFileName(date);
File result = new File(fileName);
return result;
}
private String provideFileName(LocalDate date) {
// ... some complex business logic to generate file name based on date... ;)
return fileName;
}
}
There is a private method provideFileName() that does some complicated things and let's say it's hard to test if you would test only createSomeImportantReport().
See what changes if you externalize that functionality.
class ReportCreator {
private FileNameProvider fileNameProvider;
public File createSomeImportantReport(LocalDate date) {
File result = new File(fileNameProvider.provideFileName(date));
return result;
}
}
class FileNameProvider {
public String provideFileName(LocalDate date) {
return ......;
}
}
You now have option to test that thing separately, focus on what's important in that particular case.
Despite the fact that I don't see a use case for a private getter, you can use the package private access level. This is the default access level so you don't have to specify it. You can then test it by adding the test class in the same package name in the test directory. For instance the class is located in src/main/java/application and the test class can then be located in src/test/java/application.
Use Java Reflection for that:
Test test = new Test();
Method getArrayListMethod = test.getClass().getDeclaredMethod("getArrayList", null);
getArrayListMethod.setAccessible(true);
ArrayList<String> list = (ArrayList<String>) getArrayListMethod .invoke(test);
System.out.println(list); // Prints the list
Create your Test object, use the method getClass() and get the method declared on that class by its name.
Then set that method accessible dynamically. If you know the data type that it returns, then cast it to it.

Java: How to update textArea from different class while a loop is running?

I am developing a little program to make reservations and I am stuck at how to update the textArea from a different class while I am doing some stuff in a loop ?
So for example I have this piece of code:
GUI class contains the very basic layout of GUI plus this method:
public class MyGUI extends JFrame implements ActionListener
{
public MyGUI()
{
...
}
....
public void setResultArea(String text)
{
resultArea.append(text);
}
}
Test class
public static void writeToTextArea()
{
while(true)
{
if(message = "Hello World")
...
modify text area
}
}
I look around but I couldn't find something related. Any ideas?
At the end of the day, your test class needs a reference to your MyGUI class. There are various ways to give this reference:
make a setter method in the test class which takes and stores a MyGUI.
give the test class a constructor which takes and stores a MyGUI.
This is not considering best-practices of software design. That means, since I don't know the whole of your project, I can't comment on the best approach.
Once the test class "has" an instance of MyGUI, you can call the "setResultArea" method on it from the place you've written "modify text area".

Java Object creating a different Class object

I'll just start by saying that I am a new to Java programming. I've got this problem:
I have this class:
public class Unit
{
public boolean status;
public Unit()
{
status=true;
}
public boolean getstatus(){
return status;
}
public void setstatus(boolean pStatus){
status=pStatus;
}
}
And i need a second class called TestUnit that, when i use it to create a object, unpon creation it creates also a Unit class.
How can i do this? Help would be appreciated.
P.S.: I'm working with Bluej.
If your TestUnit class is in the same package, then it can just create a new Unit instance like this:
Unit u = new Unit();
But they ought really to be in different packages, for instance
com.giaky.unit
com.giaky.unit.test
In that case, you need to import the class into your TestUnit class. You do that with a line at the top of the file, just under the package statement, like this:
import com.giaky.unit.Unit;
After that, you can create instances of your Unit class just as if it were in the same package, with
Unit u = new Unit();
Your IDE will help you with all of this: it should be able to help you move the classes to different packages, if needed, and also to import classes from one package into another.
Importing is something you'll need a lot, every time you use a class from the JDK libraries.
Are you look for this?
public class TestUnit{
private Unit unit;
public TestUnit(){
unit = new Unit();
}
}
public class TestUnit{
private Unit unit;
public TestUnit(){
this.unit=new Unit();}
}
}
//you can add other methods and variables as needed :)
You can do something like this:
public class TestUnit {
//You can create a reference to handle your Unit instance
private Unit myunit;
//Provide a constructor to assign a unit you create
public TestUnit(Unit myunit) {
this.myunit = myunit;
}
//Or provide a default constructor which instances a default one
public TestUnit() {
this.myunit = new Unit();
}
}
I think that is a way you can handle, I know very good answers will come, but this is my approach according to your description :)
Regards and happy coding :).

Not able to write the testcases for inner class using EasyMock

I am new to the EasyMock. I need to test my class using the EasyMock. but here the problem is my class has inner class and this inner class is instatiated in the outer class's method and calling the method of inner class by passing some parameters. I am not sure how to write the test case for this scenario.
Please help me write the test case for this.
Any help or suggetions are highly appreciated.
public class ServiceClass implements ServiceInterface {
public void updateUSer(USer) {
//some logic over here.
sendEmailNotice(subject, vTemplate);
}
private sendEmailNotice(subject, vTemplate) {
MimeMessagePrepator eNotice = new PrepareEmailNotice(subject, vTemplate);
MailSender.send( eNotice );
}
public class PrepareEmailNotice implements MimeMessagePrepator {
// some local variables.
public PrepareEmailNotice(subject, vTemplate) {
subject = subject;
vTemplate = vTemplate;
}
public void prepare( MimeMessage message) {
MimeMessageHealper helper = new MimeMessageHealper(message, true);
// setting the mail properties like subject, to address, etc..
}
}
Thanks.
First of all you need to think about what is the class responsibility.
At should it be doing with who should it be speaking?
Once you've clearly identified the dependencies you need to see how you can handle them in your code.
You might need do to perform some refactoring in order to conform to the dependency inversion principle.
For example here you have a dependency to the MailSender class but you won't be able to mock it as this dependency is "hard coded".
There is a good video about that: http://www.youtube.com/watch?v=XcT4yYu_TTs

Categories