Mockito - Verify that a static method inside an Object's method is called - mockito

I have a problem like this
public class ErrorLog {
public static void increment(String exception) {
// do something
}
}
import ErrorLog;
public class Calculator {
public int division(int a, int b) {
if (b == 0) {
ErrorLog.increment("Divide by Zero");
} else {
return a / b;
}
}
}
I want to verify the number of calls to divide, but when I have divide by zero situation, somehow verify that the static method ErrorLog.increment is called (with the exact string as the parameter).
With Mockito spy, I can do something like this to ensure calls to the divide method.
Calculator c = new Calculator();
Calculator calcSpy = spy(c);
c.division(6, 3);
c.division(1, 0);
verify(calcSpy, times(2)).division(anyInt(), anyInt());
I also keen to verify something like this
verify(ErrorLog, times(1)).increment("Divide by Zero");
I explored PowerMockito verifyStatic constructs and mockStatic, checked this one too mockito verify method call inside method but in my case the method that is called inside the object is static.

You are right verifyStatic doesn't have any ways to check the method being called.
But there is a workaround. See if this works for you.
The way to mock a static method is to use
PowerMockito.mockStatic(ErrorLog.class)
But you can also use another variant
PowerMockito.mockStatic(ErrorLog.class, invocationOnMock -> {
assertEquals("something", invocationOnMock.getArgumentAt(0, String.class));
return null;
});
ErrorLog.increment("something");
If you do not mock ErrorLog class, you cannot verify

you are right.
If you use a static method you will have problems with tests and dependency injection and this is a case.
You should transform the ErrorLog in a Singleton and then you could verify it with spy.
ex:
public class ErrorLog {
private static ErrorLog = new ErrorLog();
public static ErrorLog getInstance() {
return errorLog;
}
public void increment(String exception) {
// do something
}
}
import ErrorLog;
public class Calculator {
public int division(int a, int b) {
if (b == 0) {
ErrorLog.getInstance()increment("Divide by Zero");
} else {
return a / b;
}
}
}
And from this point you can you the following snippet to test the invocations:
ErrorLog errorLog = ErrorLog.getInstance();
ErrorLog errorLogSpy = spy(errorLog);
verify(errorLogSpy , times(1)).increment(any());

Thanks for the responses, it guided me in the right direction. The thing that did the trick to me is this (I am using TestNG framework).
package com.apple.sample.powermock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
#PrepareForTest({ErrorLog.class})
public class TestStaticMethods extends PowerMockTestCase {
#Test
public void testSpy() throws Exception {
PowerMockito.mockStatic(ErrorLog.class, invocation -> {
assertEquals("Division by Zero", invocation.getArgument(0, String.class));
return null;
});
new Math().division(10, 0);
}
}

Related

PowerMockito calls real method on Mocked Object when defining second "when" clause

I am trying to define some different mocked behaviours when a method is called with different parameters. Unfortunately, I find that the second time I try to mock the given method on a (mocked) class, it runs the actual method, causing an exception because the matchers are not valid parameters. Anyone know how I can prevent this?
manager = PowerMockito.mock(Manager.class);
try {
PowerMockito.whenNew(Manager.class).withArguments(anyString(), anyString())
.thenReturn(manager);
} catch (Exception e) {
e.printStackTrace();
}
FindAuthorityDescriptionRequestImpl validFindAuthorityDescription = mock(FindAuthorityDescriptionRequestImpl.class);
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(anyString(), anyString())).thenCallRealMethod();
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(Matchers.eq(VALID_IK),
Matchers.eq(VALID_CATEGORY_NAME))).thenReturn(validFindAuthorityDescription);
PowerMockito.when(manager.processRequest(Matchers.any(FindAuthorityDescriptionRequest.class)))
.thenThrow(ManagerException.class);
PowerMockito.when(manager.processRequest(Matchers.eq(validFindAuthorityDescription)))
.thenReturn(generateValidAuthorityDescriptionResponse());
The following code is a working example based on your mock setup (I've added dummy classes to make it runnable).
The code also contains asserts to verify that the mocked methods return expected values. Also, the real method createFindAuthorityDescriptionRequest is only called once.
Note: This was tested with `powermock 2.0.7` and `mockito 2.21.0`.
If issues persist, I'd suggest checking if the real method is not additionally called from somewhere else in your program (other than the code quoted in your problem statement).
package com.example.stack;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.powermock.api.mockito.PowerMockito.mock;
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.example.stack.*")
public class StackApplicationTests {
private static final String VALID_IK = "IK";
private static final String VALID_CATEGORY_NAME = "CATEGORY_NAME";
private static final Object VALID_RESPONSE = "RESPONSE";
#Test
public void test() {
Manager manager = mock(Manager.class);
try {
PowerMockito.whenNew(Manager.class).withArguments(anyString(), anyString())
.thenReturn(manager);
} catch (Exception e) {
e.printStackTrace();
}
FindAuthorityDescriptionRequestImpl validFindAuthorityDescription = mock(FindAuthorityDescriptionRequestImpl.class);
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(anyString(), anyString())).thenCallRealMethod();
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(eq(VALID_IK), eq(VALID_CATEGORY_NAME)))
.thenReturn(validFindAuthorityDescription);
PowerMockito.when(manager.processRequest(any(FindAuthorityDescriptionRequest.class)))
.thenThrow(ManagerException.class);
PowerMockito.when(manager.processRequest(eq(validFindAuthorityDescription)))
.thenReturn(VALID_RESPONSE);
// verify that the mock returns expected results
assertEquals(Manager.REAL_RESULT, manager.createFindAuthorityDescriptionRequest("any", "any"));
assertEquals(validFindAuthorityDescription, manager.createFindAuthorityDescriptionRequest("IK", "CATEGORY_NAME"));
assertThrows(ManagerException.class, new ThrowingRunnable(){
#Override
public void run( ) {
manager.processRequest(new FindAuthorityDescriptionRequestImpl());
}
});
assertEquals(VALID_RESPONSE, manager.processRequest(validFindAuthorityDescription));
}
}
interface FindAuthorityDescriptionRequest {}
class FindAuthorityDescriptionRequestImpl implements FindAuthorityDescriptionRequest {}
class ManagerException extends RuntimeException {}
class Manager {
public static FindAuthorityDescriptionRequestImpl REAL_RESULT = new FindAuthorityDescriptionRequestImpl();
public Manager(String s1, String s2) {}
public FindAuthorityDescriptionRequest createFindAuthorityDescriptionRequest(String ik, String category) {
return REAL_RESULT;
}
public Object processRequest(FindAuthorityDescriptionRequest request) {
return null;
}
}

How do I create Enumerable<Func<>> out of method instances

I am creating a rule set engine that looks kinda like a unit test framework.
[RuleSet(ContextA)]
public class RuleSet1
{
[Rule(TargetingA)]
public Conclusion Rule1(SubjectA subject)
{ Create conclusion }
[Rule(TargetingA)]
public Conclusion Rule2(SubjectA subject)
{ Create conclusion }
[Rule(TargetingB)]
public Conclusion Rule3(SubjectB subject)
{ Create conclusion }
}
[RuleSet(ContextB)]
public class RuleSet2
{
[Rule(TargetingB)]
public Conclusion Rule1(SubjectB subject)
{ Create conclusion }
[Rule(TargetingA)]
public Conclusion Rule2(SubjectA subject)
{ Create conclusion }
[Rule(TargetingB)]
public Conclusion Rule3(SubjectB subject)
{ Create conclusion }
}
public class Conclusion()
{
// Errorcode, Description and such
}
// contexts and targeting info are enums.
The goal is to create an extensible ruleset that doesn't alter the API from consumer POV while having good separation-of-concerns within the code files. Again: like a unit test framework.
I am trying to create a library of these that expose the following API
public static class RuleEngine
{
public static IEnumerable<IRuleSet> RuleSets(contextFlags contexts)
{
{
return from type in Assembly.GetExecutingAssembly().GetTypes()
let attribute =
type.GetCustomAttributes(typeof (RuleSetAttribute), true)
.OfType<RuleSetAttribute>()
.FirstOrDefault()
where attribute != null
select ?? I don't know how to convert the individual methods to Func's.
}
}
}
internal interface IRuleset
{
IEnumerable<Func<SubjectA, Conclusion>> SubjectARules { get; }
IEnumerable<Func<SubjectB, Conclusion>> SubjectBRules { get; }
}
...which allows consumers to simply use like this (using foreach instead of LINQ for readability in this example)
foreach (var ruleset in RuleEgine.RuleSets(context))
{
foreach (var rule in ruleset.SubjectARules)
{
var conclusion = rule(myContextA);
//handle the conclusion
}
}
Also, it would be very helpful if you could tell me how to get rid of "TargetingA" and "TargetingB" as RuleAttribute parameters and instead use reflection to inspect the parameter type of the decorated method directly. All the while maintaining the same simple external API.
You can use Delegate.CreateDelegate and the GetParameters method to do what you want.
public class RuleSet : IRuleSet
{
public IEnumerable<Func<SubjectA, Conclusion>> SubjectARules { get; set; }
public IEnumerable<Func<SubjectB, Conclusion>> SubjectBRules { get; set; }
}
public static class RuleEngine
{
public static IEnumerable<IRuleSet> RuleSets() // removed contexts parameter for brevity
{
var result = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetCustomAttributes(typeof(RuleSetAttribute), true).Any()
let m = t.GetMethods().Where(m => m.GetCustomAttributes(typeof(RuleAttribute)).Any()).ToArray()
select new RuleSet
{
SubjectARules = CreateFuncs<SubjectA>(m).ToList(),
SubjectBRules = CreateFuncs<SubjectB>(m).ToList()
};
return result;
}
}
// no error checking for brevity
// TODO: use better variable names
public static IEnumerable<Func<T, Conclusion>> CreateFuncs<T>(MethodInfo[] m)
{
return from x in m
where x.GetParameters()[0].ParameterType == typeof(T)
select (Func<T, Conclusion>)Delegate.CreateDelegate(typeof(Func<T, Conclusion>), null, x);
}
Then you can use it like this:
var sa = new SubjectA();
foreach (var ruleset in RuleEngine.RuleSets())
{
foreach (var rule in ruleset.SubjectARules)
{
var conclusion = rule(sa);
// do something with conclusion
}
}
In your LINQ query you headed straight for RuleSetAttribute, and so lost other information. If you break the query in several lines of code you can get methods from the type with GetMethods(), and then you can call GetCustomAttribute<RuleAttribute>().

Calling method from overridden Java class.

I have a problem with calling an overriden method from java class.
I have the following Java class:
public class Base
{
int state = 0;
public void called()
{
System.out.println("Hello, from called method: " + state);
}
public String getFirst()
{
return "From Base;
}
//
...
//
}
I use a groovy script to override getFirst() that so that it calls called()
def base = [ getFirst : {
called() // this line has an error
"From Second"
}] as Base
base.getFirst()
How do I implement the this?
You can't use the proxy magic in that way... At the time of the Maps declaration, it doesn't know it's going to be a Proxy for Base, so it will throw the error
Why not just do it the normal way?
def base = new Base() {
public String getFirst() {
called()
"from me"
}
}

how do I register multiple interface implementations with multiple keys in castle windsor?

I have a validation interface like so:
public interface IValidation<T> {
bool IsValid(T item, ref AggregateException fail);
}
I have a file importer that needs several validation interfaces
public FileImporter {
IEnumerable<IValidation<Patient>> Validators { get; set; }
public FileImporter(IWindsorContainer container) {
// the ResolveAll method does not do this
Validators = container.ResolveAll<IValidation<Patient>>("fileValidation");
}
}
I also have another class that has more validators but uses some of the same ones used in FileImporter.
public PatientService {
IEnumerable<IValidation<Patient>> Validators { get; set; }
public PatientService(IWindsorContainer container) {
// the ResolveAll method does not do this
Validators = container.ResolveAll<IValidation<Patient>>("userInputValidation");
}
}
For example I have two validators LastNameValidator and DateOfBirthValidator. LastNameValidator is used in both theFileImporterand thePatientService.DateOfBirthValidatoris only used in thePatientService` class. The implementation of these two classes are below the question.
My question is how can i wire up these two classes so that they are used as described above. And what method call should I make to resolve them?
public class LastNameValidator : IValidation<Patient> {
public bool IsValid(Patient p, ref AggregateException fail) {
var isValid = !string.IsNullOrWhitespace(p.LastName))
if (!isValid)
// update fail
return isValid;
}
}
public class DateOfBirthValidator : IValidation<Patient> {
public bool IsValid(Patient p, ref AggregateException fail) {
if (!p.DateOfBirth.HasValue) {
// update fail, can't be empty
return false;
}
if (p.DateOfBirth.Value > DateTime.Now) {
// update fail, can't be in future
return false;
}
return true;
}
}
I would consider the Typed Factory Facility. You could register your validators with the names "lastnamevalidator" and "dobvalidator". Then create a factory interface for grabbing those specific validators. You just need the interface -- the facility will do the implementation:
public interface IValidatorFactory
{
IValidator GetLastNameValidator();
IValidator GetDobValidator();
}
Now pass the IValidatorFactory to your component. This also removes the need to pass the Windsor container around (which isn't a good idea as it tightly couples your code to Windsor and makes unit testing more difficult).
Now just call the factory methods to access the particular validator each component needs.
UPDATE:
Still not clear on which part of your system is going to determine which IValidators to use, but maybe this would work. Use a marker inteface that is based on IValidator.
public interface IFileValidator : IValidator
{
}
public interface IUserInputValidator : IValidator
{
}
Now have your validators implement the marker interfaces depending on where they are going to be used -- and remember you can implement multiple interfaces so validators can be used in multiple situations. Example:
public class FileValidator : IFileValidator
{
public bool IsValid()
{
return false;
}
}
public class DobValidator : IUserInputValidator, IFileValidator
{
public bool IsValid()
{
return false;
}
}
public class LastNameValidator : IUserInputValidator
{
public bool IsValid()
{
return true;
}
}
Change the factory interface to return just the specific types of validators:
public interface IValidatorFactory
{
IFileValidator[] GetFileValidators();
IUserInputValidator[] GetUserInputValidators();
}
Now register the validators accorindg to their "type". If a validator has multiple uses, make sure to add a .Forward<> defintion for Windsor:
var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<IValidatorFactory>().AsFactory(),
Component.For<IFileValidator>().ImplementedBy<FileValidator>(),
Component.For<IUserInputValidator>().ImplementedBy<LastNameValidator>(),
Component.For<IFileValidator>().Forward<IUserInputValidator>().ImplementedBy<DobValidator>()
);

In C#, how can I pass a method from another class using Func<T>?

I have a state machine that needs to call a different method on each object from a List of objects depending on the state I'm in. Basically I'm trying to refactor the code that has a loop in each case statement of my state machine so that it looks like the code below. However I cannot seem to figure out how to pass the relevant method to my refactored function (not to mention I then don't know how to call it on each item)
Any help would be appreciated.
Here's the example code:
public class MyOtherType
{
public bool Method1()
{ return false; }
public bool Method2()
{ return false; }
public bool Method3()
{ return false; }
public bool Method4()
{ return false; }
}
public class MyType
{
public enum MyState
{
DoSomething1,
DoSomething2,
DoSomething3,
DoSomething4
}
private MyState State = MyState.DoSomething1;
List<MyOtherType> MyListOfObjects = new List<MyOtherType>() { new MyOtherType(), new MyOtherType() };
private void StateMachine()
{
switch (State)
{
case MyState.DoSomething1:
//How do I pass this in? Do I need to set it up differnetly?
Process(() => MyOtherType.Method1());
break;
case MyState.DoSomething2:
Process(() => MyOtherType.Method2);
break;
case MyState.DoSomething3:
Process(() => MyOtherType.Method3);
break;
case MyState.DoSomething4:
Process(() => MyOtherType.Method4);
break;
}
}
private void Process(Func<bool> method)
{
foreach (MyOtherType item in MyListOfObjects)
{
//How do I call the method on each item?
if (item.method())
{
//Do something
}
}
}
}
I would suggest to get rid of such switch blocks and decouple each specific method from a state by introducing flexible map of strategy per state so it could be easily changed or even injected:
IDictionary<MyState, Func<bool>> strategyMap;
1) Fill it in
// if idea is to access methods without instance of MyOtherType -
// make all methods and class itself static so you can access it
// like MyOtherType.Method1
strategyMap = new Dictionary<MyState, Func<bool>>();
strategyMap.Add(MyState.DoSomething1, myOtherTypeInstance.Method1);
2) Call appropriate strategy depends on state instead of switch(State)
if (starategyMap.ContainsKey(State))
{
// pass in an associated strategy
Process(starategyMap[State]);
}
Feel free to ask in case of any questions
One possible solution is to make the methods static and take the class reference they shall operate on as a parameter:
public class MyOtherType
{
public static bool Method1(MyOtherType instance)
{
return instance == null;
}
}

Resources