Java Object creating a different Class object - java

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 :).

Related

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.

How to make JUnit test fall down if constuctor is present?

I am learning JUnit and Test Driven Development practice. I have empty Money interface:
public interface Money {
}
CommonMoney class which implements Money interface:
public class CommonMoney implements Money {
private CommonMoney() {
}
public static Money create(String decimalPart, Currency currency) {
return new Money() {
};
}
}
And MoneyTest class which tests CommonMoney
public class MoneyTest {
// some test cases before
#Test
public void shouldNotCreateCommonMoneyObjectWithEmptyConstructor() {
#SuppressWarnings("unused")
Money money = new CommonMoney();
fail();
}
}
For now test case shouldNotCreateCommonMoneyObjectWithEmptyConstructor is red, but it should be green if constructor of CommonMoney is private and red if it is public. Is it possible to make test case like this? And how can I do it?
Is it possible to make test case like this?
Yes, it is possible to implement this test by using java reflection, for example see this question. Otherwise, you cannot test, that the private constructor is present, from outside of that class - the code just won't compile.
However, it doesn't really make sense to test this. Access modifiers are really there for developer convenience and to limit the access scope. Arguably, scope limitation is also done for convenience.
Your tests should cover public API and not look at private implementation.
This is not the sort of thing you need to test.
As Agad pointed out, the code won't compile the way it is anyway, because by making the constructor private you've made it impossible to create the object with an empty constructor.
The compiler is effectively doing the check for you, so you don't need to write a specific test to check for it.

Junit testing a class which extends WizardPage

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()?

jMockit's access to a private class

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

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