Not able to write the testcases for inner class using EasyMock - java

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

Related

Java - How to test the non-abstract methods of an abstract class?

I have an abstract class that features no abstract methods... How would one go about testing this? Can I simply import it into a test class and go about business as usual?
Example:
public abstract class SomeAbstractClass implements SomeOtherClass {
// Some variables defined here
private static final String dbUrl = System.getProperty("db.url");
// Some public methods
public String doSomethingToUrl(String url) {
url = url + "/takeMeSomewhereNice";
}
}
Say I pass in an arg for db.url of localhost:8080, and I wanted to test that the doSomethingToUrl method did output the new string... Would it still be in this format?
public class TestUrl {
SomeAbstractClass sac = new SomeAbstractClass();
#Test
public void testUrlChange() throws Exception {
String testUrl = "localhost:8080";
assertThat("localhost:8080/takeMeSomewhereNice",
sac.doSomethingToUrl(testUrl));
}
}
You wouldn't be able to create an instance of just SomeAbstractClass, no - but you could create an anonymous subclass:
private SomeAbstractClass sac = new SomeAbstractClass() {};
You may well want to create a concrete subclass just for the sake of testing though - so that any time you do add abstract methods, you just need to put them there.
While I suspect you could use a mocking framework for this, I suspect it would add more complexity for little benefit, unless you need to check under what situations the abstract methods are called. (Mocks are great for interaction testing, but can be brittle for other purposes.) It could easily make for more confusing error messages (due to the infrastructure involved) as well.
You cannot initialize an abstract class, so your test class wouldn't compile as is.
You can either use an anonymous instance (the example below should suffice):
SomeAbstractClass sac = new SomeAbstractClass(){};
However, I would actually recommend you mock the class by means of a mocking framework such as Mockito or EasyMock.

Test tightly coupled classes in Java

I have this original code:
public SomeClass(int parameter) {
this.someProperty = parameter;
this.apiObject = new SomeApiClass(someProperty);
for(i=0; i < 2; i++)
apiObject.setApiProperty(i, "Hello World");
}
The code works perfectly fine. But the problem arises when I try to test the same.
#Mock
private SomeApiClass someApiClass;
private SomeClass someClass;
#Before
public void setUp() throws Exception {
someClass = new SomeClass(3);
}
#Test
public void shouldCreateSomeClass() {
verify(someApiClass, times(2)). setApiProperty(anyInt(),anyString());
}
I understand why this test wouldn't pass. This would work if I change the constructor to this:
public SomeClass(int parameter, SomeApiClass someApiClass) {
...
}
How do I test the original code if I do not want to inject SomeApiClass to the constructor and also can't afford to provide any getters in it.
PS: Please ignore typos in the code. Typed it on the fly.
It's good to think about testability when you design your class and also to differentiate parameters and dependencies.
Dependencies are objects that the class will rely on to get its work done. They generally don't change throughout the lifecycle of the dependee object.
Parameters are more localized than dependencies. They are expected to change in between calls to the methods of the object.
In the original code, it looks like the work done in the constructor for SomeClass should really go inside a method:
public class SomeClass {
public void doWork(int parameter) {
//
}
}
Inside the method, if you are only interested in instantiating SomeApiObject with the parameter, then why not follow the Law of Demeter and pass in directly SomeApiObject as a parameter:
public void doWork(SomeApiObject someApiObject) {
//
}
Then the consumer does the work:
someClass.doWork(new SomeApiObject(3));
and it can be tested by passing in a mocked SomeApiObject as a parameter:
//act
someClass.doWork(mockedSomeApiObject);
//assert
verify(mockedSomeApiObject).someVerification();
However, if you want a combination of parameters and dependencies you can use a Factory as a dependency:
public class SomeClass {
private final SomeApiObjectFactory someApiObjectFactory;
public SomeClass(SomeApiObjectFactory someApiObjectFactory) {
this.someApiObjectFactory = someApiObjectFactory;
}
public void doWork(int parameter) {
SomeApiObject someApiObject = someApiObjectFactory.create(parameter);
//etc
}
Then you can now test the class since you have a way to supply mocks on which behaviour can be verified:
SomeApiObject mockSomeApiObject = Mockito.mock(SomeApiObject.class);
when(mockSomeApiObjectFactory.create(anyInt()).thenReturn(mockApiObject);
Aside from all of that there are ways of using Powermockito to test your original class as it is without alteration but these are not ideal and it is best to refactor if possible so you can use plain Mockito to test. This will give you good OO habits. Good luck!

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

Testing Private method using mockito

public class A {
public void method(boolean b){
if (b == true)
method1();
else
method2();
}
private void method1() {}
private void method2() {}
}
public class TestA {
#Test
public void testMethod() {
A a = mock(A.class);
a.method(true);
//how to test like verify(a).method1();
}
}
How to test private method is called or not, and how to test private method using mockito?
Not possible through mockito. From their wiki
Why Mockito doesn't mock private methods?
Firstly, we are not dogmatic about mocking private methods. We just
don't care about private methods because from the standpoint of
testing private methods don't exist. Here are a couple of reasons
Mockito doesn't mock private methods:
It requires hacking of classloaders that is never bullet proof and it
changes the api (you must use custom test runner, annotate the class,
etc.).
It is very easy to work around - just change the visibility of method
from private to package-protected (or protected).
It requires me to spend time implementing & maintaining it. And it
does not make sense given point #2 and a fact that it is already
implemented in different tool (powermock).
Finally... Mocking private methods is a hint that there is something
wrong with OO understanding. In OO you want objects (or roles) to
collaborate, not methods. Forget about pascal & procedural code. Think
in objects.
You can't do that with Mockito but you can use Powermock to extend Mockito and mock private methods. Powermock supports Mockito. Here's an example.
Here is a small example how to do it with powermock
public class Hello {
private Hello obj;
private Integer method1(Long id) {
return id + 10;
}
}
To test method1 use code:
Hello testObj = new Hello();
Integer result = Whitebox.invokeMethod(testObj, "method1", new Long(10L));
To set private object obj use this:
Hello testObj = new Hello();
Hello newObject = new Hello();
Whitebox.setInternalState(testObj, "obj", newObject);
While Mockito doesn't provide that capability, you can achieve the same result using Mockito + the JUnit ReflectionUtils class or the Spring ReflectionTestUtils class. Please see an example below taken from here explaining how to invoke a private method:
ReflectionTestUtils.invokeMethod(student, "saveOrUpdate", "From Unit test");
Complete examples with ReflectionTestUtils and Mockito can be found in the book Mockito for Spring.
Official documentation Spring Testing
By using reflection, private methods can be called from test classes.
In this case,
//test method will be like this ...
public class TestA {
#Test
public void testMethod() {
A a= new A();
Method privateMethod = A.class.getDeclaredMethod("method1", null);
privateMethod.setAccessible(true);
// invoke the private method for test
privateMethod.invoke(A, null);
}
}
If the private method calls any other private method, then we need to spy the object and stub the another method.The test class will be like ...
//test method will be like this ...
public class TestA {
#Test
public void testMethod() {
A a= new A();
A spyA = spy(a);
Method privateMethod = A.class.getDeclaredMethod("method1", null);
privateMethod.setAccessible(true);
doReturn("Test").when(spyA, "method2"); // if private method2 is returning string data
// invoke the private method for test
privateMethod.invoke(spyA , null);
}
}
**The approach is to combine reflection and spying the object.
**method1 and **method2 are private methods and method1 calls method2.
Think about this in terms of behaviour, not in terms of what methods there are. The method called method has a particular behaviour if b is true. It has different behaviour if b is false. This means you should write two different tests for method; one for each case. So instead of having three method-oriented tests (one for method, one for method1, one for method2, you have two behaviour-oriented tests.
Related to this (I suggested this in another SO thread recently, and got called a four-letter word as a result, so feel free to take this with a grain of salt); I find it helpful to choose test names that reflect the behaviour that I'm testing, rather than the name of the method. So don't call your tests testMethod(), testMethod1(), testMethod2() and so forth. I like names like calculatedPriceIsBasePricePlusTax() or taxIsExcludedWhenExcludeIsTrue() that indicate what behaviour I'm testing; then within each test method, test only the indicated behaviour. Most such behaviours will involve just one call to a public method, but may involve many calls to private methods.
Hope this helps.
I was able to test a private method inside using mockito using reflection.
Here is the example, tried to name it such that it makes sense
//Service containing the mock method is injected with mockObjects
#InjectMocks
private ServiceContainingPrivateMethod serviceContainingPrivateMethod;
//Using reflection to change accessibility of the private method
Class<?>[] params = new Class<?>[]{PrivateMethodParameterOne.class, PrivateMethodParameterTwo.class};
Method m = serviceContainingPrivateMethod .getClass().getDeclaredMethod("privateMethod", params);
//making private method accessible
m.setAccessible(true);
assertNotNull(m.invoke(serviceContainingPrivateMethod, privateMethodParameterOne, privateMethodParameterTwo).equals(null));
You're not suppose to test private methods. Only non-private methods needs to be tested as these should call the private methods anyway. If you "want" to test private methods, it may indicate that you need to rethink your design:
Am I using proper dependency injection?
Do I possibly needs to move the private methods into a separate class and rather test that?
Must these methods be private? ...can't they be default or protected rather?
In the above instance, the two methods that are called "randomly" may actually need to be placed in a class of their own, tested and then injected into the class above.
There is actually a way to test methods from a private member with Mockito. Let's say you have a class like this:
public class A {
private SomeOtherClass someOtherClass;
A() {
someOtherClass = new SomeOtherClass();
}
public void method(boolean b){
if (b == true)
someOtherClass.method1();
else
someOtherClass.method2();
}
}
public class SomeOtherClass {
public void method1() {}
public void method2() {}
}
If you want to test a.method will invoke a method from SomeOtherClass, you can write something like below.
#Test
public void testPrivateMemberMethodCalled() {
A a = new A();
SomeOtherClass someOtherClass = Mockito.spy(new SomeOtherClass());
ReflectionTestUtils.setField( a, "someOtherClass", someOtherClass);
a.method( true );
Mockito.verify( someOtherClass, Mockito.times( 1 ) ).method1();
}
ReflectionTestUtils.setField(); will stub the private member with something you can spy on.
I don't really understand your need to test the private method. The root problem is that your public method has void as return type, and hence you are not able to test your public method. Hence you are forced to test your private method. Is my guess correct??
A few possible solutions (AFAIK):
Mocking your private methods, but still you won't be "actually" testing your methods.
Verify the state of object used in the method. MOSTLY methods either do some processing of the input values and return an output, or change the state of the objects. Testing the objects for the desired state can also be employed.
public class A{
SomeClass classObj = null;
public void publicMethod(){
privateMethod();
}
private void privateMethod(){
classObj = new SomeClass();
}
}
[Here you can test for the private method, by checking the state change of the classObj from null to not null.]
Refactor your code a little (Hope this is not a legacy code). My funda of writing a method is that, one should always return something (a int/ a boolean). The returned value MAY or MAY NOT be used by the implementation, but it will SURELY BE used by the test
code.
public class A
{
public int method(boolean b)
{
int nReturn = 0;
if (b == true)
nReturn = method1();
else
nReturn = method2();
}
private int method1() {}
private int method2() {}
}
Put your test in the same package, but a different source folder (src/main/java vs. src/test/java) and make those methods package-private. Imo testability is more important than privacy.
In cases where the private method is not void and the return value is used as a parameter to an external dependency's method, you can mock the dependency and use an ArgumentCaptor to capture the return value.
For example:
ArgumentCaptor<ByteArrayOutputStream> csvOutputCaptor = ArgumentCaptor.forClass(ByteArrayOutputStream.class);
//Do your thing..
verify(this.awsService).uploadFile(csvOutputCaptor.capture());
....
assertEquals(csvOutputCaptor.getValue().toString(), "blabla");
Building on #aravind-yarram's answer: Not possible through mockito. From their wiki
So what's the OO way of testing private methods? Private methods with complex logic might be a sign that your class is violating the principle of single responsibility and that some of the logic should be moved to a new class.
Indeed, by extracting those private methods to public methods of more granular classes, you can unit test them without breaking the encapsulation of your original class.

How to write unit test using mock object?

The more I read mock example, the more I get confused...
I have classA method eat() that calls FatDude class eatThemAll()
public class classA {
FatDude dude = new FatDude();
public String eat() {
String result = dude.eatThemAll();
}
}
public class FatDude {
public String eatThemAll() {
return "never full";
}
}
Now I want to test classA eat() method by mocking FatDude class.
public class MockFatDude extends FatDude {
//override
public String eatThemAll() {
return "very full";
}
}
------------- test --------------
public class DoTest {
public void runTest() {
classA cl = new ClassA();
String out = cl.eat();
assertEqual(out, "very full");
}
}
This DoTest runTest() won't use MockFatDude class of course. One way I can think is to change the code to pass FatDude to eat() method of ClassA like:
public class classA {
public String eat(FatDude dude) {
String result = dude.eatThemAll();
}
}
Then change my test method to:
public class DoTest {
public void runTest() {
classA cl = new ClassA();
String out = cl.eat(new MockFatDude());
assertEqual(out, "very full");
}
}
But as you can see, I had to change the source code to meet my need.
Is this the right way to do? What if I am not allowed to change my source code?
I know if I apply TDD concept, it is OK to change source code but I would like to hear
some opinion or advice if what I have shown above is right way to do.
Mocking and the Dependency Inversion Principle (DIP) go hand in hand, and in most languages, Mocks work best by decoupling classes by means of interfaces.
In your instance, this will work without you needing to change code: (Edit : I mean, in future, if you design your app this way, you won't need to change code to mock dependencies :))
Abstract an interface IDude
Concrete classes FatDude (and MockFatDude) should implement IDude interface
provide a mechanism for an IDude instance to be 'set' or injected into classA - Dependency Injection (constructor or get / sets); or Service Locator pattern work best (to replace a concrete classfactory)
Also note that many mocking frameworks actually allow you to build up the Mock concrete class 'on the fly' (see MoQ et al), so you can create the functionality of MockFatDude directly in your unit test.
Yes. You've stumbled on some good design directly because of your unit test. If you look more closely, you'll see that you removed the coupling between classA and FatDude. Now FatDude can be an interface for behavior that gets passed in when needed. ClassA doesn't need to know what kind of FatDude it's getting, or how to construct a FatDude (with cheeseburgers?).
Your solution is exactly what I would have done. There's nothing wrong with changing your code to accomodate TDD, as long as you understand the reasons and the benfits/drawbacks to making such changes.

Categories