I'm trying something similar to this, and only one of the #Before methods gets called:
public abstract class ControllerBase extends Controller {
#Before
static void foo() {
// this actually gets called
}
}
public class ConcreteController extends ControllerBase {
#Before
static void bar() {
// This DOES NOT get called
}
public static void index() {
render();
}
}
Is this a bug, feature, or something I'm doing wrong?
You're trying to do something weird. And I think your example doesn't match your question. Did you mean to implement ConcreteController on ControllerBase? Rather than both of them extending on Controller?
The #before tag is a concrete class tag. Only the one in the concrete class will get executed.
You can #override the original function, but I don't think that's what you were looking for.
The best way to get what you want is to remove #before from the abstract and from the concrete function call the implemented function you want to run.
public abstract class ControllerBase extends Controller {
static void foo() {
// this actually gets called
}
}
public static class ConcreteController extends Controller {
#Before
static void bar() {
foo();
// This DOES NOT get called
}
public static void index() {
render();
}
}
Yes, Play! will call all the methods in the inheritance hiererchy annotated with #Before.
The problem I ran into was that the #Before I was using was actually org.junit.Before instead of play.mvc.Before !
Related
I have a test case that mock a static method of java.lang.System class:
#Test
fun `getLocalTime()`() {
// Arrange
val staticMock = Mockito.mockStatic(System::class.java)
Mockito.`when`(System.currentTimeMillis()).thenReturn(1000L)
// Action
val res = deviceTimeProvider.getLocalTime()
// Assert
Truth.assertThat(res).isEqualTo(1000L)
staticMock.close()
}
But when I run the test, I got this error:
org.mockito.exceptions.base.MockitoException: It is not possible to
mock static methods of java.lang.System to avoid interfering with
class loading what leads to infinite loops
Why does this happen? How can I mock methods of java.lang.System class?
While Mockito since 3.4.0 version allows mocking static methods it is not allowed to mock the Thread and System static methods, see this comment on github
Finally note that Mockito forbids mocking the static methods of System (and Thread). Those methods are to much cemented into class loading which happens in the same thread. At some point, we might add instrumentation to class loading to temporarily disable the static mocks within it to make mocking these classes, too, where we also would need to disable their intensification properties. You can however easily mock Instant.now().
If you like ugly solutions you can still mock System with PowerMockito
#PrepareForTest(System.class)
public class TestCase {
#BeforeClass
public void setup() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(1000L);
}
...
But I would avoid mocking System classes if possible. You can still wrap it in method and mock this method.
To mock the static methods of java.lang.System class with the help of Mockito.
Create an interface i.e ISystem.java
public interface ISystem {
String getProperty(String name);
Long getCurrentTimeInMillis();
}
2- Create the implementation class of ISystem interface i.e ISystemImpl.java
public class ISystemImpl implements ISystem {
#Override
public String getProperty(final String name) {
return System.getProperty(name);
}
#Override
public Long getCurrentTimeInMillis() {
return System.currentTimeMillis();
}
}
3- Use Isystem.java inside your DeviceTimeProvider.java class.
public class DeviceTimeProvider {
#NonNull private final ISystem mISystem;
public DeviceTimeProvider(ISystem iSystem){
mIsystem = iSystem;
}
public Long getLocalTime(){
return mIsystem.getCurrentTimeInMillis()
}
}
4- Now finally mock the ISystem interface inside your test class.
public class DeviceTimeProviderTest {
private ISystem mISystem;
private DeviceTimeProvider sut;
#Before
public setup(){
mIsystem = mockito.mock(ISystem.class)
sut = new DeviceTimeProvider(mISystem);
}
#Test
public void getDeviceLocalTime(){
Long expectedTime = 1000L;
mockit.when(mISystem.getCurrentTimeInMillis()).thenReturn(expectedTime);
Long actualTime = sut.getLocalTime();
Assert.assertEquals(actualTime, expectedTime);
}
}
OUTPUT
I want to mock static method which is called within other static method.
public class MyClass
{
public static void methodA(String s)
{
...
methodB(s);
...
}
public static void methodB(String s)
{
...
}
}
So, I want to mock methodA, but I want to skip calling methodB.
I tried almost all solutions that I was able to find, without any success. Every time methodB is called.
Some solutions that I used:
PowerMockito.suppress(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.stub(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.mockStatic(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
And many others...
Anyone have an idea how to solve this problem?
In my opinion you should Spy your class instead of mocking it.
In that situation all the static methods will be called with real implementation and on top of that you could instruct to not call methodB:
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
class MyClassTest
{
#Test
public void test()
{
PowerMockito.spy(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
}
}
I have written an article on Mocking Static Methods if you need a further read.
I have a class with a method that takes a single parameter. This parameter is a nested class inside the mocked class, but it is private (And static but I don't think that makes much of a difference to this). How do I go about mocking this method?
Example:
public class myClass {
public anotherObject;
public myClass(AnotherObject anotherObject) {
this.anotherObject = anotherObject;
}
public void exec() {
//Some instructions ...
//This second method is inside another completely seperate class.
anotherObject.secondMethod(new NestedClass());
}
private static class NestedClass {
public NestedClass() {
//Constructor
}
//Variables and methods, you get the picture
}
}
In the above example secondMethod(...) is the method that I want to mock.
All attempts to find other examples of this problem just return results relating to mocking a single private nested class, or mocking static classes, which aren't completely relevant to this and don't seem to provide any work around that I can figure out.
EDIT:
I'm looking for some sort of solution that looks like this:
#Test
public void testExec() {
AnotherObject anotherObject = mock(AnotherObject.class);
when(anotherObject.secondMethod(any(NestedClass.class))).thenReturn(0);
MyClass testThisClass = new MyClass(anotherObject);
}
Notes: I'm not allowed to make modifications to the code I'm afraid, I am only allowed to create these tests to make sure the current implementation works later down the line when modification are made to it.
If I am understanding the requirement correctly, add one method say executeSecondMethod(). Call this method in your main method class.
public class myClass {
public void exec() {
//Some instructions ...
secondMethod(new NestedClass());
}
public void secondMethod(NestedClass example) {
//Some instructions that I want to just mock out...
}
private static class NestedClass {
//Variables and methods, you get the picture
}
public static executeSecondMethod(){
secondMethod(new NestedClass()); // pass the nested class object here
}
}
public class mainClass{
public static void main(){
executeSecondMethod();
}
}
I have a Mainclass that I need to test which is dependent on other class.
Now I am creating a mock for that class
How to test void methods using easymock
MainClass{
mainClassMethod(){
dependencyClass.returnVoidMethod();
//other code
}
}
TestClass{
#Before
setUpMethod(){
DependencyClass dependencyClassMock = EasyMock.createMock(DependencyClass.class);
}
#Test
testMainClassMethod(){
EasyMock.expect(dependencyClassMock.returnVoidMethod()).andRetur //this is not working
dependencyClassMock.returnVoidMethod();
EasyMock.expectLastCall().anyTimes(); //If I use this, it is invoking the method.
}
}
//My dependency class code
DependencyClass implements ApplicationContextAware{
private static ApplicationContext applicationContext;
private static final String AUTHENTICATION_MANAGER = "authenticationManagers";
returnVoidMethod(){
ProviderManager pm = (ProviderManager) getApplicationContext().getBean(AUTHENTICATION_MANAGER); //this is returning null
}
//othercode
//getters and setters of application context
}
As described in the Easymock Documentation you don't put the method inside an expect() (since there is no return). You can just call the mocked method by itself and if it is in "record" mode then it is implied an expect.
dependencyClassMock.returnVoidMethod();
If you need to throw an Exception or say the method can be called anyTimes() you can use expectLastCall()
#Test
public void testMainClassMethod(){
dependencyClassMock.returnVoidMethod();
EasyMock.expectLastCall().anyTimes();
...
//later to replay the mock
EasyMock.replay(dependencyClassMock);
//now this method is actually called
dependencyClassMock.returnVoidMethod();
}
EDIT : Just noticed that you don't have the dependencyClassMock as field:
public class TestClass{
DependencyClass dependencyClassMock
#Before
setUpMethod(){
dependencyClassMock = EasyMock.createMock(DependencyClass.class);
}
...//rest of class is as described above
#dkatzel
the test is completely wrong..... you are calling manually a method and the you verify if it was called...of course it was! ...that's not the right way (my opinion)
A better way (my opinion) would be to extend the mehod class you would like to test, override that method and in the body just put a boolean variable as a flag to k now if the method was called or not....you don't even need to use EasyMock
Example
Class DependencyClass {
public void returnVoidMethod() {
[.... content ...]
}
}
Class A_test {
#Test
public void checkVoidMethodCalled() {
A_mod obj = new A_mod();
mainClassMethod();
assertTrue(obj.called);
}
Class A_mod extends DependencyClass {
boolean called = false;
#Override
public void returnVoidMethod() {
called = true;
}
}
}
You are welcome.
I want create unit test to test a class which contains another object. I have created a mock to this second object.
When I test a method of my first class, I want verify if the functions of the second object are called. For this, I use the function verify(mock).myfunction();
My problem is that the same function of my object 2 can be called by several function of my first class.
When I write the test class, I write a test function by function but it seems that the "times" isn't reset at the beginning of a test method.
I don't know if I am clear, therefore, an example :
public class Main {
public Object o = createObject();
public void function1(){
o.function();
}
public void function2(){
o.function();
}
public Object createObject() {
return new Object() ;
}
public class MainTest {
private static Main main;
#BeforeClass
public static void setUp() throws Exception {
final Object mockO = mock(Object.class);
main = new Main() {
#Override
public Object createObject() {
return mockO;
}
};
}
#Test
public void testfunction1(){
verify(main.world[0], never()).function();
main.function1();
verify(main.world[0]).function();
}
#Test
public void testfunction2(){
verify(main.world[0], never()).function();
main.function2();
verify(main.world[0]).function();
}
If I test testfunction1() and testfunction2() ignored, it's work.
If I test testfunction2() and testfunction1() ignored, it's work.
But if the two tests are executed, I have an error :
org.mockito.exceptions.verification.NeverWantedButInvoked:
Object.function();
Never wanted here :
-> at test.MainTest.testfunction1
but invoked here :
at source.Main.function2
How I can test independently the two functions?
Rename your setUp() method into something else, make it a non-static method, and make it #Before and not #BeforeClass:
private Main main;
#Before
public void initMain()
{
// what you already do
}
#BeforeClass methods run once before all tests in a class, while #Before methods are run once before each test.