Test method of Singleton object using Powermock - singleton

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.

Related

Retrieving private method information using Javassist

I am using JavaAssist to read class information. It is a good and very useful tool.
However, what I have noticed is that it does enumerate or returns the private methods of the class.
Is there a way I can retrieve private methods?
You can use CtClass.getDeclaredMethods( ) to get the information about private methods.
Or as suggested above reflection works fine.
Try giving this a read to know more about the features of javassist.
In order to get all the methods, which also contains the private methods of a a class you could use reflection:
import java.lang.reflect.*;
public class ExampleClass {
public static void main(String[] args) {
ExampleClass cls = new ExampleClass ();
Class c = cls.getClass();
// returns the array of Method objects
Method[] m = c.getDeclaredMethods();
for(int i = 0; i < m.length; i++) {
System.out.println("method found = " + m[i].toString());
}
}
public ExampleClass () {
// no argument constructor
}
public void publicMethod(String string1) {
// NOPE
}
private void privateMethod(Integer i) {
// NOPE
}
}

Moq class with constructors ILogger and options netcore 2.1 vs2017 getting error

I need to mock a class that has parameters in the constructor by I cannot figure out how you do it using moq. It crashes
Constructor arguments cannot be passed for interface mocks.
See my attempt below:
[Fact]
public async Task MyTest()
{
var mySettings= GetMySettings();
var mySettingsOptions = Options.Create(mySettings);
var mockLogger = Mock.Of<ILogger<MyClass>>();
var mock=new Mock<IMyClass>(mySettings,mockLogger);
mock.Setup(x=>x.DoSomething(It.IsAny<string>().Returns("todo");
}
public class MyClass : IMyClass
{
private readonly ILogger<MyClass> logger;
private readonly MySettings mySettings;
public MyClass(IOptions<MySettings> settings,ILogger<MyClass>logger)
{
this.logger = logger;
this.mySettings = settings.Value;
}
public string DoSomething(string myarg)
{
//omitted
}
}
How do you do it? many thanks
EDITED
In order to mock repository and test the behaviour i also need to mock the other classes that have constructors in it. Hope makes sense
public class MyService:IMyService
{
private MyClass myclass;
private OtherClass otherClass;
private Repository repository;
public MyService(IRepository repository,IMyClass myclass,IMyOtherClass otherClass)
{
this.myclass=myClass;
this.otherClass=otherClass;
this.repository=repository;
}
public void DoStuff()
{
bool valid1=myclass.Validate(); //mock myclass
var valid2=otherClass.Validate(); //mock otherClass
if(Valid1 && valid2)
{
repository.GetSomething();//this is really what I am mocking
}
//etc..
}
}
It doesn't matter if your class constructor has parameters or not, because you're working with its mock object.
var mock = new Mock<IMyClass>();
mock.Setup(x=>x.DoSomething(It.IsAny<string>()).Returns("todo");
Then you can use this mock to your repository constructor:
var myService = new MyService(repositoryMock.Object, mock.Object, otherClassMock.Object);
You are getting this error because you are trying to create a mock of an interface (IMyClass in this case) with constructor values. It seems like you are trying to test the method in the class MyClass, therefore you should be creating a moq of this class.
To clarify change
var mock=new Mock<IMyClass>(mySettings,mockLogger); to var mock=new Mock<MyClass>(mySettings,mockLogger);

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

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.

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 do Setup of mocks with Ninject's MockingKernel (moq)

I'm having a really hard time trying to figure how I can do .SetupXXX() calls on the underlying Mock<T> that has been generated inside the MockingKernel. Anyone who can shed some light on how it is supposed to work?
You need to call the GetMock<T> method on the MoqMockingKernel which will return the generated Mock<T> on which you can call your .SetupXXX()/VerifyXXX() methods.
Here is an example unit test which demonstrates the GetMock<T> usage:
[Test]
public void Test()
{
var mockingKernel = new MoqMockingKernel();
var serviceMock = mockingKernel.GetMock<IService>();
serviceMock.Setup(m => m.GetGreetings()).Returns("World");
var sut = mockingKernel.Get<MyClass>();
Assert.AreEqual("Hello World", sut.SayHello());
}
Where the involved types are the following:
public interface IService { string GetGreetings(); }
public class MyClass
{
private readonly IService service;
public MyClass(IService service) { this.service = service; }
public string SayHello()
{
return string.Format("Hello {0}", service.GetGreetings());
}
}
Note that you can access the generated Moq.MockRepository (if you prefer it over the SetupXXX methods) with the MoqMockingKernel.MockRepository property.