doing a verify on void method using powerMock - powermock

There is a local instance of a class being instantiated inside a method.
eg
class TestMe{
public void foo()
{
A a = new A();
a.setState(this);
}
}
class A
{
private B b;
public void setState(TestMe tm)
{
b.doSomething(); //returns void
b.doSomethingAdditional(); //returns void
}
}
When testing foo, using powerMock, I wanted to do a verify to ensure that methods doSomething() and doSomethingAdditional() are called. I was looking something along the lines of the Mockito.verify(ObjectName).functionName() to do. Any suggestions??

PowerMock works in combination with Mockito. You should still have all the functionality to verify using Mockito calls.
Once you mock B, when you mock its functions and then pass it into A you can use the Mockito.verify.
verify(mockBObject).doSomething();
verify(mockBObject).doSomethingAdditional();
This may need a few extra steps to hook your mock object into A, since you don't have a constructor where you can define B passed in, or have some constructor to hook into. If you are just having A initialize B at the creation of A, you can use some PowerMockito tools to tell it what to do. Just mocking B will not do, because when your A is setup, it doesn't know to use your mocked object in its code as the B internal.
PowerMockito.whenNew(B.class).withNoArguments().thenReturn(mockBObject);
As of right now B is never setup or initialized, so it could cause some issues. If B is a static singleton object that you are assuming is created somewhere else, you can do similar mocking of the static getInstance() call to return a mock of B.

Related

how to mock an instance method invocation from static method while writing junit for static method?

how to mock an instance method invocation from static method while writing junit for static method?I'm writing tests for existing code.
class A
{
public static D methodX()
{
B b = new B();
C c = b.doSomething();
}
}
class B
{
public C doSomething()
{
return C;
}
}
class Atest
{
#Test
public void testMethodX()
{
B b =Mockito.mock(B.class);
Mockito.when(b.doSomething()).thenReturn(new C());
A.methodX();
// some assertions
}
}
By your tag selection you already know that you need to go for PowerMockito.
In order to inject a mocked version of B class i would do the following:
A class
class A
{
public static D methodX()
{
B b = getBInstance();
C c = b.doSomething();
}
static B getBInstance(){
return new B();
}
}
Test Class
#RunWith(PowerMockRunner.class)
#PrepareForTest(A.class)
class Atest
{
#Test
public void testMethodX()
{
B b =Mockito.mock(B.class);
PowerMockito.stub(PowerMockito.method(A.class, "getBInstance")).toReturn(b);
Mockito.when(b.doSomething()).thenReturn(new C());
A.methodX();
// some assertions
}
}
Thanks to PowerMockito.stub(PowerMockito.method call you will just mock the getBInstance static method and in the end call the real A.methodX implementation.
Another completely different approach: do not write un-testable code. static is an abnormality within good OO designs; to the first step is to simply not write static methods.
And when you have good reasons to still do so; then write them in a way that allows you reasonable unit-test them.
Yes, it is possible to turn to PowerMock(ito) to get this solved, but the more sane approach is to simple fix your production design.
The PowerMock(ito) frameworks come at certain cost; and can easily be avoided.
Thus, my answer: learn how to create testable code; and simply forget about PowerMock (you can start by watching these videos).

How to mock static method chain call using easymock-powermock?

I want to mock below method chain using easymock-powermock,
OtherClass oc = SampleClass.getInstance().getSampleMethod(new StringReader("ABC");
getInstance () is a singleton method.
getSampleMethod() is a public method.
When I try to use expect/andReturn getting null.
I am not sure if you are setting the expectations at once to the whole method chain but that is not how it works. You have to set the expectation for each and every method call separately.
In your case, as first method call is a static call you should use powermock and set the expectation and return the mocked instance for it. Then you should add the expectation for second method call. I have given the sample code below Please check if it works in your case.
#RunWith(PowerMockRunner.class)
#PrepareForTest({SampleClass.class})
public class SimpleClassTest{
#Test
public void test(){
PowerMock.mockStatic(SampleClass.class);
SampleClass sampleClassInstance = EasyMock.createMock(SampleClass);
EasyMock.expect(SampleClass.getInstance).andReturn(sampleClassInstance);
EasyMock.expect(sampleClassInstance.getSampleMethod(/*required parameter goes here*/).andReturn(/*Otherclass instance goes here*/);
PowerMock.replayAll();
EasyMock.replay(sampleClassInstance);
}
}

Mockito: pass mocked object as parameter to a function (when call the function)

I am using Mockito to write a simple unit test.
I have a function to test:
public void doSomething() {
foo.getStudent(new School());
}
My test case:
#Test
public void testDoSomething() {
Foo mockedFoo = Mockito.mock(Foo.class);
School mockedSchool = Mockito.mock(School.class);
// I want to pass the mocked school as parameter when food.getStudent(school) is called
// how to pass mocked school to method?
when(mockedFoo.getStudent(???))
// run the method under test
myService.doSomething();
}
I want to pass the mockedSchool as parameter when foo.getStudent(school) is called, how to declare this in Mockito?
Seems Mockito only has when(...).thenReturn(), but is there something like when(...).thenPassArgument(mockedObject) ?
The problem lies in the way you instantiate the School class in the doSomething method; as you instantiate it on the spot you can't overload that instantiation with the mock using mockito.
If you pass it as a parameter of doSomething you should be able to perform this.
I believe PowerMock can help you if you want to overload an internal construction.
As you don't need to assert into the School instance and just pass a mocked instance as a parameter, you can do the following:
mockedBar.getStudent(Mockito.isA(School.class));
Please read the Mockito documentation about the isA(java.lang.Class<T> clazz) method.

Accessing non public Method of Object in JUNIT

Hi I am new to unit testing. Is it possible to access methods that are private?
A very simple example
ObjectA
----------
File file;
private void setupFile (){
//do something
file = "C:\file.dat"
}
In TestCase
File sth = ObjectA.setupFile();
assertNotNull(sth);
I am unable to test whether the file variable is null in method ObjectA.setup()
as I cannot run ObjectA.setupFile()
I am not sure about whether doing like this make sense in terms of unit testing.
So is that a better practice to write every method returning sth and set them public for easier unit testing?
Thanks in advance
In general, you should avoid changing the access of a method/field to enable testing. If you do this then you risk developers using the method directly.
However, if you do need to, then making it protected as Deco says is a good way, so it's accessible from the JUnit tests. If you do this, make sure that it is well documented that this is an method for internal use.
A better way is to test the behaviour of the public methods; you shouldn't care about internal implementation details of a class, so you should only be testing public methods. It's hard to tell from your code, but presumably, the setupFile() has effects later on other methods, so you can test those effects, not the fact that file is not null.
External dependencies (such as dependencies on file system, environment variables) can be worked around in your tests, or injected directly into the class. For the general principle, see my answer to How to test code dependent on environment variables using JUnit?
If it is not absolutely necessary to have the method as private, you can have it as package private (i.e. default access) so that you can call it directly in a JUnit test.
Package private methods can only be used in the package that they are declared, and do not become part of the API of the class. You declare a method package private by putting no modifier on it's declaration.
Here's an example to demonstrate:
public class MyClass() {
int foo;
public MyClass() {
this.foo = 0;
}
void notSoComplexCalculationMethod(int a) {
foo = a * 2;
}
//Other methods here . . .
}
public class MyClassTest extends TestCase {
private MyClass myClass;
protected void setUp() {
super.setUp();
myClass = new MyClass();
}
public void testNotSoComplexCalculationMethod() {
int a = 2;
assertEquals(4, myClass.notSoComplexCalculationMethod(a));
//Unit test passes, yay! Now you've tested a package private method.
}
}

Creating a .NET object in IronRuby when a static .New() method is defined

It seems impossible to create an object using its default constructor when there is a static .New() method defined on the class:
.NET class:
public class Tester
{
public static void New()
{
Console.WriteLine("In Tester.New()");
}
public Tester()
{
Console.WriteLine("In constructor");
}
}
IronRuby code:
Tester.new
Tester.New
Both of these lines call Tester.New(), not the constuctor. It seems impossible to call the constructor of the Tester class.
Is there a workaround, or is this a bug?
The first one is just an unavoidable ambiguity. If you want to make CLI classes look like Ruby classes, you have no choice but to map the constructor to a new method. So, if you have both a real new method and a synthesized one which maps to a constructor, whatever you do, either the synthetic method shadows the real one or the other way around. Either way, you lose.
That's why all CLI classes have a synthetic clr_new method:
Tester.clr_new
# In constructor