Mockito doNothing with Mockito.mockStatic - mockito

I'm using Mockito, along with mockito-inline for mocking static methods. I'm trying to apply doNothing or similar behavior, to a static void method. The following workaround work, but I think that there should have a more convenient way to achieve this with less code.
try (MockedStatic<UtilCalss> mock = Mockito.mockStatic(UtilCalss.class)) {
mock.when(() -> UtilCalss.staticMethod(any()))
.thenAnswer((Answer<Void>) invocation -> null);
}
If it's a non-static method, we could simply do:
doNothing().when(mock).nonStaticMethod(any());
But I want to do the same for a static method.

You don't need to stub that call.
doNothing is a default behaviour of a void method called on a mock.

mockito-inline include mockito-core :
<!-- Mockito-inline include Mockito-code in same version - Useful for Mock static method -->
<!-- See https://asolntsev.github.io/en/2020/07/11/mockito-static-methods/ -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.6.28</version>
</dependency>
And if static method you are testing return nothing => don't use mock.when => just execute the method you want to test and verify :
try (MockedStatic<UtilClass> mock = Mockito.mockStatic(UtilClass.class)) {
mock.when(() -> UtilClass.staticMethod(any()))
.thenAnswer((Answer<Void>) invocation -> null);
App.main(null); // example : I'm testing main method from App class
mock.verify(UtilClass::staticMethod); // I verify static method from UtilClass was called.
}
resources :
Mocking static methods with Mockito
https://github.com/mockito/mockito/issues/2027 - cf rimuln comment on 16 Oct 2020

Related

Mocking a public method that has a private method call inside using Mockito (not Powermockito)

I am testing for methodA() in the class :
class Test{
public String methodA(String str){
...
methodB("s1","s2");
...
}
private String methodB(String s1, String s2){
...
}
}
What I have tried in my test class:
Method methodBReflect = Test.class.getDeclaredMethod("methodB", Test.class,String.class, String.class);
methodBReflect.setAccessible(true);
Test testForSpy=new Test();
Test spyTest=spy(testForSpy);
doReturn("return string").when(spyTest..)... // <-- What should be done here?
//methodBReflect.invoke(spyTest, "args1","args2");
P.S: I don't need a solution using powermock as I have some organizational constraints using it.
You shouldn't be testing that method A calls method B. You should test that method A does what method A is supposed to do - that is, it gives the correct output for whatever input you give it. Your test shouldn't care whether method A works by calling method B, or by doing all its processing inline.
Therefore, there's no need to mock or stub anything. Your tests will consist of a bunch of calls to method A, along with verification that the output is what you expect.
You only need to use Mockito (or some other mocking framework) when you're testing a class that interacts with another class entirely; not when the class under test interacts with itself.

What is the use of a static initialization block in Groovy?

What is the use of the static initialization block in Groovy. Why does Geb use it? If the use of it is the same as in Java, then how can you initialize non-declared fields in a situtation like this?
class ManualsMenuModule extends Module {
static content = {
toggle { $("div.menu a.manuals") }
linksContainer { $("#manuals-menu") }
links { linksContainer.find("a") }
}
void open() {
toggle.click()
waitFor { !linksContainer.hasClass("animating") }
}
}
Some answers to your questions are provided in the section about the content DSL of the Geb manual.
The DSL is implemented using Groovy's methodMissing() mechanism and modification of the delegate of the closure assigned to the static content field. If you are interested in digging deeper then you can always look at the implementation in PageContentTemplateBuilder.
I'm not expert on Geb, I can only explain the groovy meaning of the code.
1st off, it's not the static initialization block like in java. In those lines static content = {...} you are assigning to a static variable a Closure instance which is evaluated and executed LATER (hence, lazy).
The closure represents a (part of) a Geb's Groovy Builder which is called by Geb framework to register/perform some tasks.
There's no Java counterpart to achieve the same, and that's the reason why groovy-based frameworks are so nice to use for testing purposes and they follow the general rule of thumb:
test code should be more abstract then the code under test
UPDATE:
This line:
toggle { $("div.menu a.manuals") }
can be rewritten like
toggle( { $("div.menu a.manuals") } )
or
def a = { $("div.menu a.manuals") }
toggle a
so it's a method invocation and not an assignment. In groovy you can omit the brackets in some cases.

how do I configure my testng IReporter to accept parameters

IReporter is an interface that has a single void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) method. I would like to make the behavior of the reporter configurable so I can pass options to it when run on the commandline. The documentation explains how to pass parameters to a reporter on the commandline:
-reporter The extended configuration for a custom report listener. Similar to the -listener option, except that it allows the
configuration of JavaBeans-style properties on the reporter instance.
Example: -reporter
com.test.MyReporter:methodFilter=insert,enableFiltering=true You
can have as many occurences of this option, one for each reporter that
needs to be added.
So it seems I should be able to call testng with -reporter com.my.reporter:key1=value1,key2=value2
but WHERE do I get the values passed in.
I've looked at the XMLReporter provided by testng, and it has a private final XMLReporterConfig config = new XMLReporterConfig(); line, but I can't find out how the config is ever populated.
Magic, that's how it's done :-) It appears it looks for instance variables on your class that implements IReporter with the same name. It does need a stronger type than Object or def though it seems. Here's an example.
class MyReporter implements IReporter {
int foo; //<-- populated when instantiated
#Override
void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
println "foo = ${foo}"
}
}
And then to execute it:
testng ... -reporter 'full.path.to.MyReporter:foo=42'

AssertWasCalled on method in SystemUnderTest

I'm getting into TDD; using nUnit and RhinoMocks 3.5.
I'm trying to figure out how to AssertWasCalled on a method in the SystemUnderTest (SUT). My understanding is that you can't mock the system under test. In fact, my current test results in an exception because the I'm using the AssertWasCalled on the SUT.
OrdersPresenter:
public void OnViewLoad_GetOrders()
{
var orders = GetOrders();
View.Model.Orders = orders;
}
public List<Orders> GetOrders()
{
return _ordersRepository.GetAll();
}
OrdersPresenterTest:
_ordersPresenter = new OrdersPresenter(_view, _ordersRepository);
[Test]
public void OnViewLoad_GetOrders_Should_Call_GetOrders()
{
_view.Raise(v => v.LoadOrders += _ordersPresenter.OnViewLoad_GetOrders, view, new EventArgs);
_ordersPresenter.AssertWasCalled(d => d.GetOrders); // Getting non-mock exception here
}
How do I Assert GetOrders was called in the SUT? I haven't been able to figure it out in the docs.
Any help is greatly appreciated.
Edit:
I understand the GetOrders method in the SUT should be private. I went back thru Roy Osherove's Art of Unit Testing to see how to test private methods. Roy says making a method public (to test against) is not necessarily a bad thing, so I will keep it public.
So I've written a test for GetOrders and I assert the return value ShouldBe a list of orders. That said, I believe I need to restructure my test for OnViewLoad_GetOrders by stubbing the value I get from GetOrders and asserting the results of my actions on that object.
Can someone confirm and explain?
You can not use AssertWasCalled() on not-mocked objects. Just abstract class OrdersPresenter by an interface (use Extract Interface refactoring technique) and then
var ordersPresenter = MockRepository.GenerateMock<IOrderRepository>();
view.Raise(...);
_ordersPresenter.AssertWasCalled(d => d.GetOrders);
BTW,
for me it is not clear why RhinoMocks not used generic parameter constraint for AssertWasCalled
public static void AssertWasCalled<T>(this T mock, Action<T> action,
Action<IMethodOptions<object>> setupConstraints)
Basically T is not limited, but I believe it would be better limit it to somethign like IMockMarkerInterface

Mock static method with no parameters in Groovy

I need to mock a static method. I'm using the EMC approach described at Mocking static methods using groovy. Like this
TestDaemon.metaClass.'static'.newDownloadManager = {downloadManager}
The method newDownloadManager has no parameters and for some reason it is not replaced. The original code is called. In debug mode I can see that the closure that I define has a parameter. May be that's the reason? How can I define a closure without parameters? Or how can I mock a static method with no parameters?
Meta class changes aren't visible to Java code. Groovy can't help you to mock a static method that gets called from Java code. You will have to use something like JMockit instead (or refactor the code under test).
A closure written like that has an implicit parameter. Write the closure with { -> } syntax. Example:
x = { println "foo" }
y = { -> println "foo" }
assert x.parameterTypes as List == [Object]
assert y.parameterTypes as List == []

Resources