Jmockit Expectations/Verifications for calls to private methods when testing a public method? - jmockit

Can anyone advise if it is possible to use an expectations/verifications to test that private methods are being called the-right-number-of-times/right-parameters.
The Class under test has been Mocked-Up - with one private method overridden.
Am Testing a public method which calls into a number of private methods.
I wish to know if it is possible to verify the calls to other private methods which will be called when the public method is being executed ?
Some idea of the code/class under test;
public class UnderTest {
public void methodPublic(arg 1){
.....
methodPrivate1(var1);
....
methodPrivate2(var2);
}
private void methodPrivate1(var1){
//do stuff
}
private void methodPrivate2(var1){
//do stuff
}
}
In my test case
#Test
public void stateBasedTestMethod()
{
UnderTest underTest;
new MockUp<UnderTest>() {
#Mock(invocations = 1)
private void methodPrivate2(var1) {
//do nothing in the mocked case
}
};
underTest = new UnderTest();
underTest.methodPublic(arg1);
new Verifications() {{
// Is there a way to test that methodPrivate1 has been called-once/with-expected-arguments
}};
}
Edited in response to the answer from Rogério.
I am using jmockit 1.12
and the Verifications is FAILING as the method using the provided solution is invoking the method twice as I thought from the JMockit documentation.
Failure Trace;
mockit.internal.UnexpectedInvocation: Expected exactly 1 invocation(s) of MyHelperTest$1#method3..., but was invoked 2 time(s)
Included is the full code I am using for this.
As described above - my goal is to mock one of the private methods to do nothing.
And ensure that I can verify that the other private method is called only once.
Thanks in advance and hopefully will get a better understanding if this is possible with Jmockit.
Test Code.
public class MyHelperTest {
#Test
public void testHelper(#Mocked final MyDependent myDependent) {
final MyHelper myHelper;
new MockUp<MyHelper>() {
#Mock(invocations = 1)
private void method3(MyDependent myTable) {
System.out.println("In Mocked Method");
//do nothing in the mocked case
}
};
myHelper = new MyHelper();
myHelper.method1(myDependent);
new Verifications() {{
invoke(myHelper, "method2", myDependent); times = 1;
}};
}
}
Class under test.
public class MyHelper {
public void method1(MyDependent myDependent){
method2(myDependent);
}
private void method2(MyDependent myDependent) {
myDependent.setValue(1);
method3(myDependent);
}
private void method3(MyDependent myDependent) {
myDependent.setValue(2);
}
}
Dependent Class
public class MyDependent {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

It's possible, though not recommended to mock private methods.
Using the Expectations API:
#Tested #Mocked MyHelper myHelper;
#Test
public void testHelper(#Mocked final MyDependent myDependent)
{
new NonStrictExpectations() {{ invoke(myHelper, "method3", myDependent); }};
myHelper.method1(myDependent);
new Verifications() {{ invoke(myHelper, "method2", myDependent); times = 1; }};
}
... where the invoke(...) method is statically imported from class mockit.Deencapsulation.

I noticed that if a method you want to verify is not mocked, when the static block in an Expectations or Verifications instance is executed that the code calls the method that you are trying to mark as expected or verify.
This might explain the extra invocation that you are seeing.
One suggestion: if you are already mocking the class with MockUp (and thus creating an anonymous subclass) so you can override the private method, why not change the access of the overridden private method to protected or public? Then you can create an expectation or verification on it.
You could also provide a public field "public int counter=0;" and have your overridden method increment the counter. Then you can use an assert on it after the test is complete.

Related

Verifications involving non-mocked class with mocked abstract parent

A member of my team has written a JMockit-based test method that using a Verifications instance to assert a method was invoked on the UUT, which is not mocked, but extends a mocked abstract parent (it happens to be a Hibernate repository). The test passes, but my opinion, based on the JMockit documentation, is that only mocks should be used in a Verifications instance initializer. I think the result is a false negative but my team member insists it's a valid verification call. The test itself is simple, so I've recreated it using contrived objects:
package com.acme.dataacess;
public abstract class AbstractRepository {
public final T list(Class<T> clazz, final Collection<String> keys) {
.....
}
}
package com.acme.module.dataacess
public class FooRepository extends AbstractRepository<Foo> {
public List<Foo> list() {
return getFoos(null);
}
public List<Foo> list(Collection<String> keys) {
return list(Foo.class, keys);
}
}
public class FooRepositoryTest {
#Tested
private FooRepository uut;
#Mocked
private AbstractRepository mockAbstractRepository;
#Test
public void testFoo1() {
// Execute the test.
this.uut.list(null);
// Verify the results.
new Verifications() {
{
// I don't think this is a valid verification, because the goal
// of the test is to assert a delegated method in a non-mocked
// class was invoked.
uut.list(null);
}
};
}
}
Is this a valid JMockit verification?

Test method of Singleton object using Powermock

I would like to test a public method1 as well as mock the private method createJSON of Singleton class.
public class SingletonClass {
private static SingletonClass singletonInstance = new SingletonClass();
private SingletonClass() {
}
public static SingletonClass getInstance() {
return singletonInstance;
}
public JSONObject method1(int id, String str)
throws JSONException {
JSONObject loginJSON = createJSON(id, str);
return loginJSON;
}
private JSONObject createJSON(int id, String str){
return new JSONObject().put("id", id).put("str", str);
}
}
Could anyone help on this?
It sounds like you need a partial mock. A partial mock will allow you to mock a subset of the methods of the class you are working with, but not others.
This SO post explains how to use partial mocks.

check that property setter was called

I have a class I am unit testing and all I want to do is to verify that the public setter gets called on the property. Any ideas on how to do this?
I don't want to check that a value was set to prove that it was called. I only want to ensure that the constructor is using the public setter . Note that this property data type is a primitive string
This is not the sort of scenario that mocking is designed for because you are trying to test an implementation detail. Now if this property was on a different class that the original class accessed via an interface, you would mock that interface and set an expectation with the IgnoreArguments syntax:
public interface IMyInterface
{
string MyString { get; set; }
}
public class MyClass
{
public MyClass(IMyInterface argument)
{
argument.MyString = "foo";
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void Test()
{
var mock = MockRepository.GenerateMock<IMyInterface>();
mock.Expect(m => m.MyString = "anything").IgnoreArguments();
new MyClass(mock);
mock.VerifyAllExpectations();
}
}
There are 2 problems with what you are trying to do. The first is that you are trying to mock a concrete class, so you can only set expectations if the properties are virtual.
The second problem is the fact that the event that you want to test occurs in the constructor, and therefore occurs when you create the mock, and so occurs before you can set any expectations.
If the class is not sealed, and the property is virtual, you can test this without mocks by creating your own derived class to test with such as this:
public class RealClass
{
public virtual string RealString { get; set; }
public RealClass()
{
RealString = "blah";
}
}
[TestClass]
public class Tests
{
private class MockClass : RealClass
{
public bool WasStringSet;
public override string RealString
{
set { WasStringSet = true; }
}
}
[TestMethod]
public void Test()
{
MockClass mockClass = new MockClass();
Assert.IsTrue(mockClass.WasStringSet);
}
}

How to design around lack of multiple inheritance?

Using interfaces won't work because I want a single implementation. Using this solution would end in a lot of redundant code because I plan on having quite a few sub classes (composition vs inheritance). I've decided that a problem-specific design solution is what I'm looking for, and I can't think of anything elegant.
Basically I want classes to have separate properties, and for those properties to be attached at design time to any sub class I choose. Say, I have class 'ninja'. I would like to be able to make arbitrary sub classes such as 'grayNinja' where a gray ninja will always have a sword and throwing stars. Then possibly 'redNinja' who will always have a sword and a cape. Obviously swords, stars, and capes will each have their own implementation - and this is where I can't use interfaces. The closest solution I could find was the decorator pattern, but I don't want that functionality at runtime. Is the best solution an offshoot of that? Where inside the Black Ninja class constructor, I pass it through the constructors of sword and throwingStar? (those being abstract classes)
haven't coded in a while and reading hasn't gotten me too far - forgive me if the answer is simple.
Edit: Answered my own question. I can't mark it as 'answer' until tomorrow. Please let me know if there's a problem with it that I didn't catch. All the reading this problem forced me to do has been awesome. Learned quite a bit.
You want classes to have separate properties. Have you considered coding exactly that?
For example, you want a RedNinja that is-a Ninja that has-a sword and cape. Okay, so define Ninja to have an inventory, make it accessible through Ninja, and pass in an inventory through RedNinja's constructor. You can do the same thing for behaviors.
I've done once a similar app. with a earlier "C++" compiler that supported only single inheritance and no interfaces, at all.
// base class for all ninjas
public class Ninja {
// default constructor
public Ninja() { ... }
// default destructor
public ~Ninja() { ... }
} // class
public class StarNinja: public Ninja {
// default constructor
public StarNinja() { ... }
// default destructor
public ~StarNinja() { ... }
public void throwStars() { ... }
} // class
public class KatannaNinja: public Ninja {
// default constructor
public KatannaNinja() { ... }
// default destructor
public ~KatannaNinja() { ... }
public void useKatanna() { ... }
} // class
public class InvisibleNinja: public Ninja {
// default constructor
public InvisibleNinja() { ... }
// default destructor
public ~InvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class FlyNinja: public Ninja {
// default constructor
public FlyNinja() { ... }
// default destructor
public ~FlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class InvincibleNinja: public Ninja {
// default constructor
public InvincibleNinja() { ... }
// default destructor
public ~InvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class SuperNinja: public Ninja {
StarNinja* LeftArm;
InvincibleNinja* RightArm;
FlyNinja* LeftLeg;
KatannaNinja* RightLeg;
InvisibleNinja* Body;
// default constructor
public SuperNinja() {
// -> there is no rule to call composed classes,
LeftArm = new StarNinja();
RightArm = new InvincibleNinja();
LeftLeg = new FlyNinja();
RightLeg = new KatannaNinja();
Body = new InvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
Im afraid, that the most close example is the composition design pattern. In order, to become more similar to inheritance, I make a generic base class that all composite classes share, and I make a main class that will be the result of the multiple inheritance, that has a copy of all the public methods of the component classes.
If you want to use interfaces, to enforce that main class have all important methods,
then make an interface that matches each composing class, and implemented in the main class.
public interface INinja {
public void NinjaScream() { ... }
} // class
public interface IStarNinja {
void throwStars();
} // class
public interface IKatannaNinja {
void useKatanna();
} // class
public interface IInvisibleNinja {
void becomeVisible();
void becomeInvisible();
} // class
public interface CFlyNinja {
void fly();
void land();
} // class
public interface IInvincibleNinja {
void turnToStone() { ... }
void turnToHuman() { ... }
} // class
// base class for all ninjas
public class CNinja: public INinja {
// default constructor
public CNinja() { ... }
// default destructor
public ~CNinja() { ... }
public void NinjaScream() { ... }
} // class
public class CStarNinja: public CNinja, INinja {
// default constructor
public CStarNinja() { ... }
// default destructor
public ~CStarNinja() { ... }
public void NinjaScream() { ... }
public void throwStars() { ... }
} // class
public class CKatannaNinja: public CNinja, IKatannaNinja {
// default constructor
public CKatannaNinja() { ... }
// default destructor
public ~CKatannaNinja() { ... }
public void NinjaScream() { ... }
public void useKatanna() { ... }
} // class
public class CInvisibleNinja: public CNinja, IInvisibleNinja {
// default constructor
public CInvisibleNinja() { ... }
// default destructor
public ~CInvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class CFlyNinja: public CNinja, IFlyNinja {
// default constructor
public CFlyNinja() { ... }
// default destructor
public ~CFlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class CInvincibleNinja: public CNinja, IInvincibleNinja {
// default constructor
public CInvincibleNinja() { ... }
// default destructor
public ~CInvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class CSuperNinja: public CNinja,
IKatannaNinja,
IInvisibleNinja,
IFlyNinja,
IInvincibleNinja
{
CStarNinja* LeftArm;
CInvincibleNinja* RightArm;
CFlyNinja* LeftLeg;
CKatannaNinja* RightLeg;
CInvisibleNinja* Body;
// default constructor
public CSuperNinja() {
// -> there is no rule to call composed classes
LeftArm = new CStarNinja();
RightArm = new CInvincibleNinja();
LeftLeg = new CFlyNinja();
RightLeg = new CKatannaNinja();
Body = new CInvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
I know this solution is complex, but, seems that there is not another way.
Cheers.
Alright so mix-ins through extension methods are going to be my preferred route. I couldn't figure out how to use dynamic proxies in vb.net (seemed to require libraries with lots of documentation that didn't cover specifically what I needed). Dynamic proxies also seems to be a bit dirtier of a solution than using extension methods. Composition would have been what I defaulted to if the previous two didn't work.
So one problem with extension methods, is that the code gets a little dirtier if you want to hold variables. Not much though. Another problem is that all the extension methods must be defined in modules, so the code might look a little goofy to a new eye. I will solve this by defining my interface and module with the corresponding extension method in the same file.
finally, here's some sample vb.net code if you don't want to see a full fledged example through the link.
Imports System.Runtime.CompilerServices 'for extension methods
Public Interface ISword
End Interface
Public Interface IThrowingStar
End Interface
Module ExtensionMethods
<Extension()>
Public Sub swingSword(ByVal hasASword As ISword)
Console.WriteLine("Sword has been swung")
End Sub
<Extension()>
Public Sub throwStar(ByVal hasAStar As IThrowingStar)
Console.WriteLine("Star has been thrown")
End Sub
End Module
Public Class RedNinja
Inherits Ninja
Implements IThrowingStar, ISword
Public Sub New()
End Sub
End Class
Public MustInherit Class Ninja
private curHealth as Integer
Public Sub New()
curHealth = 100
End Sub
Public Function getHP() As Integer
Return curHealth
End Function
End Class
Module Module1
Sub main()
Console.WriteLine("Type any character to continue.")
Console.ReadKey()
Dim a As New RedNinja
a.swingSword() 'prints "Sword has been swung"
a.throwStar() 'prints "Star has been thrown"
Console.WriteLine("End of program - Type any key to exit")
Console.ReadKey()
End Sub
End Module
Dirty solution, if you simply must have multiple inheritance, is using something like dynamic proxies in Java.
But I guess you're probably programming in C#, and this is language agnostic question, so here goes language agnostic answer: check out composite and factory design patterns, that should give you some ideas.
Also, it might not be needed to pass everything in constructor. Check out IoC pattern as well.

RhinoMocks Testing callback method

I have a service proxy class that makes asyn call to service operation. I use a callback method to pass results back to my view model.
Doing functional testing of view model, I can mock service proxy to ensure methods are called on the proxy, but how can I ensure that callback method is called as well?
With RhinoMocks I can test that events are handled and event raise events on the mocked object, but how can I test callbacks?
ViewModel:
public class MyViewModel
{
public void GetDataAsync()
{
// Use DI framework to get the object
IMyServiceClient myServiceClient = IoC.Resolve<IMyServiceClient>();
myServiceClient.GetData(GetDataAsyncCallback);
}
private void GetDataAsyncCallback(Entity entity, ServiceError error)
{
// do something here...
}
}
ServiceProxy:
public class MyService : ClientBase<IMyService>, IMyServiceClient
{
// Constructor
public NertiAdminServiceClient(string endpointConfigurationName, string remoteAddress)
:
base(endpointConfigurationName, remoteAddress)
{
}
// IMyServiceClient member.
public void GetData(Action<Entity, ServiceError> callback)
{
Channel.BeginGetData(EndGetData, callback);
}
private void EndGetData(IAsyncResult result)
{
Action<Entity, ServiceError> callback =
result.AsyncState as Action<Entity, ServiceError>;
ServiceError error;
Entity results = Channel.EndGetData(out error, result);
if (callback != null)
callback(results, error);
}
}
Thanks
Played around with this a bit and I think I may have what you're looking for. First, I'll display the MSTest code I did to verify this:
[TestClass]
public class UnitTest3
{
private delegate void MakeCallbackDelegate(Action<Entity, ServiceError> callback);
[TestMethod]
public void CallbackIntoViewModel()
{
var service = MockRepository.GenerateStub<IMyServiceClient>();
var model = new MyViewModel(service);
service.Stub(s => s.GetData(null)).Do(
new MakeCallbackDelegate(c => model.GetDataCallback(new Entity(), new ServiceError())));
model.GetDataAsync(null);
}
}
public class MyViewModel
{
private readonly IMyServiceClient client;
public MyViewModel(IMyServiceClient client)
{
this.client = client;
}
public virtual void GetDataAsync(Action<Entity, ServiceError> callback)
{
this.client.GetData(callback);
}
internal void GetDataCallback(Entity entity, ServiceError serviceError)
{
}
}
public interface IMyServiceClient
{
void GetData(Action<Entity, ServiceError> callback);
}
public class Entity
{
}
public class ServiceError
{
}
You'll notice a few things:
I made your callback internal. You'll need to use the InternalsVisisbleTo() attribute so your ViewModel assembly exposes internals to your unit tests (I'm not crazy about this, but it happens in rare cases like this).
I use Rhino.Mocks "Do" to execute the callback whenever the GetData is called. It's not using the callback supplied, but this is really more of an integration test. I assume you've got a ViewModel unit test to make sure that the real callback passed in to GetData is executed at the appropriate time.
Obviously, you'll want to create mock/stub Entity and ServiceError objects instead of just new'ing up like I did.