Evaluate parameter passed to mocked method called from another class - java

I am testing a class that use another class I have mocked. One of the outer classes' methods modifies an argument that is passed to the mocked class's method, and I need to check that it was modified correctly.
The code looks something like this:
public class Foo
{
public boolean performTask(String name, Integer version)
{
...
}
}
public class Bar
{
private Foo foo;
public Bar(Foo foo)
{
this.foo = foo;
}
public void doSomething(String name, Integer version)
{
boolean good = foo.performTask(name, ((version.startsWith("A")) ? null : version));
...
}
}
I need to check that if I pass a name argument that starts with A, then the second argument being passed to performTask() is null.
Edit:
As requested, this the start of the unit test:
public class BarTest
{
#Mock
private Foo mockFoo;
#Before
public void setup() throws Exception
{
MockitoAnnotations.initMocks(this);
}
#Test
public void test() throws Exception
{
Bar bar = new Bar(mockFoo);
bar.doSomething("ABC", new Integer(1));
}
}

All the examples I've seen of using verify involve calling the mock class directly. How do I use it in this case?
Exactly like that. All you need is access to the mock, which you have.
Mockito.verify(mockFoo, Mockito.times(1)).performTask("ABC", null);
If its important what the method is supposed to return (by default false),
you will need to define the behaviour using:
Mockito.when(mockFoo.performTask("ABC", null)).thenReturn(true);
Example:
#Test
public void test() throws Exception {
Mockito.when(mockFoo.performTask("ABC", null)).thenReturn(true);
Bar bar = new Bar(mockFoo);
bar.doSomething("ABC", new Integer(1));
Mockito.verify(mockFoo, Mockito.times(1)).performTask("ABC", null);
}

Related

How to run code after constructor in a Lombok builder

I have a class that I want to use Lombok.Builder and I need pre-process of some parameters. Something like this:
#Builder
public class Foo {
public String val1;
public int val2;
public List<String> listValues;
public void init(){
// do some checks with the values.
}
}
normally I would just call init() on a NoArg constructor, but with the generated builder I'm unable to do so. Is there a way for this init be called by the generated builder? For example build() would generate a code like:
public Foo build() {
Foo foo = Foo(params....)
foo.init();
return foo;
}
I'm aware that I can manually code the all args constructor, that the Builder will call through it and I can call init inside there.
But that is a sub-optimal solution as my class will likely have new fields added every once in a while which would mean changing the constructor too.
In Foo you could manually add a constructor, have that do the initialization, and put #Builder on the constructor. I know that you already know this, but I think it is the right solution, and you won't forget to add the parameter since you do want to use the code in the builder anyway.
Disclosure: I am a lombok developer.
After much trial and end error I found a suitable solution: extend the generate builder and call init() myself.
Example:
#Builder(toBuilder = true, builderClassName = "FooInternalBuilder", builderMethodName = "internalBuilder")
public class Foo {
public String val1;
public int val2;
#Singular public List<String> listValues;
void init() {
// perform values initialisation
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends FooInternalBuilder {
Builder() {
super();
}
#Override public Foo build() {
Foo foo = super.build();
foo.init();
return foo;
}
}
}
I just stumbled upon the same issue. But additionally, I wanted to add an method buildOptional() to the builder to not repeat Optional.of(Foo) each time I need it. This did not work with the approach posted before because the chained methods return FooInternalBuilder objects; and putting buildOptional() into FooInternalBuilder would miss the init() method execution in Builder...
Also, I personally did not like the presence of 2 builder classes.
Here is what I did instead:
#Builder(buildMethodName = "buildInternal")
#ToString
public class Foo {
public String val1;
public int val2;
#Singular public List<String> listValues;
public void init(){
// do some checks with the values.
}
/** Add some functionality to the generated builder class */
public static class FooBuilder {
public Optional<Foo> buildOptional() {
return Optional.of(this.build());
}
public Foo build() {
Foo foo = this.buildInternal();
foo.init();
return foo;
}
}
}
You can do a quick test with this main method:
public static void main(String[] args) {
Foo foo = Foo.builder().val1("String").val2(14)
.listValue("1").listValue("2").build();
System.out.println(foo);
Optional<Foo> fooOpt = Foo.builder().val1("String").val2(14)
.listValue("1").listValue("2").buildOptional();
System.out.println(fooOpt);
}
Doing so let's you add what I want:
Add an init() method which is executed after each object construction automatically
Adding new fields do not require additional work (as it would be for an individually written constructor)
Possibility to add additional functionality (incl. the init() execution)
Retain the complete
standard functionality the #Builder annotation brings
Don't expose an additional builder class
Even if you solved your problem before I like to share this as the solution. It is a bit shorter and adds a (for me) nice feature.
This works for me, not a complete solution, but quick and easy.
#Builder
#AllArgsConstructor
public class Foo {
#Builder.Default
int bar = 42;
Foo init() {
// perform values initialisation
bar = 451; // replaces 314
return foo;
}
static Foo test() {
return new FooBuilder() // defaults to 42
.bar(314) // replaces 42 with 314
.build()
.init(); // replaces 314 with 451
}
}

How to replace method invocation with mock?

I have a class with two methods. I want to replace invocation of second method with expected result.
Here is my class under test
public class A {
public int methodOne() {
return methodTwo(1);
}
public int methodTwo(int param) {
// corresponding logic replaced for demo
throw new RuntimeException("Wrong invocation!");
}
}
And test
public class ATest {
#Test
public void test() {
final A a = spy(new A());
when(a.methodTwo(anyInt())).thenReturn(10);
a.methodOne();
verify(a, times(1)).methodTwo(anyInt());
}
}
Why I'm get an exception when start the test?
Two things that will help you here. First, from the documentation it seems you need to use the do*() api with spy() objects. Second, to call the "real" method you need to declare it specifically using doCallRealMethod()
Here's the updated test that should work for you:
public class ATest {
#Test
public void test() {
final A a = spy(new A());
doReturn(10).when(a).methodTwo(anyInt());
doCallRealMethod().when(a).methodOne();
a.methodOne();
verify(a, times(1)).methodTwo(anyInt());
}
}

Proper usage of Mockito.verify

I'm new to unit testing and i had a simple question regarding the usage of verify method used in Mockito. here's the class i used for testing.
public class Foo{
int n = 0;
void addFoo(String a){
if(a == "a")
add(1);
}
protected void add(int num){
n =1;
}
public int get(){
return n;
}
}
And here's my Unit test.
public class FooTest {
#Mock Foo f;
#Test
public void test() {
MockitoAnnotations.initMocks(this);
f.addFoo("a");
//Passes
Mockito.verify(f).addFoo("a");
//Fails
Mockito.verify(f).add(1);
}
}
And i get a
Wanted but not invoked:
f.add(1);
-> at FooTest.test(FooTest.java:22)
However, there were other interactions with this mock:
-> at FooTest.test(FooTest.java:16)
exception.
How do you verify that add(int num) is called ?
I think you misunderstood the point of verify.
In your test, Foo f is a mock object - Foo's internal implementation is ignored, and only the behavior you recorded on it (using when(f.someMethod().thenXXX) would happen.
The point of mocking and verifying is to test interactions while ignoring the internal implementation.
In this example, you would probably have another class that uses Foo, and you'd want to test whether it invokes the correct methods of the given Foo instance.
Quick example:
Assume you have a class the uses the Foo class you presented in your question:
public class FooUser {
private Foo f;
public void setFoo(Foo f) {
this.f = f;
}
public Foo getFoo() {
return f;
}
public void addToFoo(String string) {
f.add(string);
}
}
Now, you'd want to test that FooUser#addToFoo(String) indeed invokes the correct add(String) method of Foo:
#RunWith (MockitoJUnitRunner.class)
public class FooUserTest {
#Mock Foo f;
FooUser fUser;
#Before
public void init() {
fUser = new FooUser();
fUser.setFoo(f);
}
#Test
public void test() {
fUser.addToFoo("a");
Mockito.verify(f).addFoo("a");
}

Mock a static method multiple times using JMockit within a JUnit test

I have a class with static methods that I'm currently mocking with JMockit. Say it looks something like:
public class Foo {
public static FooValue getValue(Object something) {
...
}
public static enum FooValue { X, Y, Z, ...; }
}
I have another class (let's call it MyClass) that calls Foo's static method; I'm trying to write test cases for this class. My JUnit test, using JMockit, looks something like this:
public class MyClassTest extends TestCase {
#NonStrict private final Foo mock = null;
#Test public void testMyClass() {
new Expectations() {
{
Foo.getValue((Object) any); result = Foo.FooValue.X;
}
};
}
myClass.doSomething();
}
This works fine and dandy, and when the test is executed my instance of MyClass will correctly get the enum value of Foo.FooValue.X when it calls Foo.getValue().
Now, I'm trying to iterate over all the values in the enumeration, and repeatedly run the test. If I put the above test code in a for loop and try to set the result of the mocked static method to each enumeration value, that doesn't work. The mocked version of Foo.getValue() always returns Foo.FooValue.X, and never any of the other values as I iterate through the enumeration.
How do I go about mocking the static method multiple times within the single JUnit test? I want to do something like this (but obviously it doesn't work):
public class MyClassTest extends TestCase {
#NonStrict private final Foo mock = null;
#Test public void testMyClass() {
for (final Foo.FooValue val : Foo.FooValue.values() {
new Expectations() {
{
// Here, I'm attempting to redefine the mocked method during each iteration
// of the loop. Apparently, that doesn't work.
Foo.getValue((Object) any); result = val;
}
};
myClass.doSomething();
}
}
}
Any ideas?
Instead of "mocking the method multiple times", you should record multiple consecutive return values in a single recording:
public class MyClassTest extends TestCase
{
#Test
public void testMyClass(#Mocked Foo anyFoo)
{
new Expectations() {{
Foo.getValue(any);
result = Foo.FooValue.values();
}};
for (Foo.FooValue val : Foo.FooValue.values() {
myClass.doSomething();
}
}
}
It could also be done with a Delegate, if more flexibility was required.

java.lang.IllegalStateException: missing behavior definition for the preceding method call getMessage("title")

I'm using EasyMock(version 2.4) and TestNG for writing UnitTest.
I have a following scenario and I cannot change the way class hierarchy is defined.
I'm testing ClassB which is extending ClassA.
ClassB look like this
public class ClassB extends ClassA {
public ClassB()
{
super("title");
}
#Override
public String getDisplayName()
{
return ClientMessages.getMessages("ClassB.title");
}
}
ClassA code
public abstract class ClassA {
private String title;
public ClassA(String title)
{
this.title = ClientMessages.getMessages(title);
}
public String getDisplayName()
{
return this.title;
}
}
ClientMessages class code
public class ClientMessages {
private static MessageResourse messageResourse;
public ClientMessages(MessageResourse messageResourse)
{
this.messageResourse = messageResourse;
}
public static String getMessages(String code)
{
return messageResourse.getMessage(code);
}
}
MessageResourse Class code
public class MessageResourse {
public String getMessage(String code)
{
return code;
}
}
Testing ClassB
import static org.easymock.classextension.EasyMock.createMock;
import org.easymock.classextension.EasyMock;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ClassBTest
{
private MessageResourse mockMessageResourse = createMock(MessageResourse.class);
private ClassB classToTest;
private ClientMessages clientMessages;
#Test
public void testGetDisplayName()
{
EasyMock.expect(mockMessageResourse.getMessage("ClassB.title")).andReturn("someTitle");
clientMessages = new ClientMessages(mockMessageResourse);
classToTest = new ClassB();
Assert.assertEquals("someTitle" , classToTest.getDisplayName());
EasyMock.replay(mockMessageResourse);
}
}
When I'm running this this test I'm getting following exception:
java.lang.IllegalStateException: missing behavior definition for the preceding method call getMessage("title")
While debugging what I found is, it's not considering the mock method call
mockMessageResourse.getMessage("ClassB.title") as it has been called from the construtor (ClassB object creation).
Can any one please help me how to test in this case.
Thanks.
You need to call EasyMock.replay(mock) before calling the method under test. After calling the method under test you can call EasyMock.verify(mock) to verify the mock is called.
Next you need to add another expect call with the "title" argument since you call it twice.
Code:
EasyMock.expect(mockMessageResourse.getMessage("title")).andReturn("title");
EasyMock.expect(mockMessageResourse.getMessage("ClassB.title")).andReturn("someTitle");
EasyMock.replay(mockMessageResourse);
clientMessages = new ClientMessages(mockMessageResourse);
classToTest = new ClassB();
Assert.assertEquals("someTitle" , classToTest.getDisplayName());
EasyMock.verify(mockMessageResourse);
In my case, it was caused by the omission of a return value specification (andReturn(...)).
http://www.smcmaster.com/2011/04/easymock-issue-1-missing-behavior.html for more details.
This can have various causes (someMock is the name of your mocked Object in this answer).
On the one side it can be that you need to expect the call via
expect(someMock.someMethod(anyObject()).andReturn("some-object");
like in Reda's answer.
It can also be that you forgot to call replay(someMock) before you used the mock, like you can see in Julien Rentrop's answer.
A last thing that is possible that wasn't mentioned here is that you used the mock somewhere else before in a test and forgot to reset the mock via reset(someMock).
This can happen if you have multiple Unit Tests like this:
private Object a = EasyMock.createMock(Object.class);
#Test
public void testA() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
#Test
public void testB() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
This will fail on one test with the IllegalStateException, because the mock a was not reset before being used in the next test. To solve it you can do the following:
private Object a = EasyMock.createMock(Object.class);
#Test
public void testA() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
#Test
public void testB() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
#After
public void tearDown() throws Exception {
reset(a); // reset the mock after each test
}
You should put your call to replay after the expect calls, and before you use your mock. In this case you should change your test to something like this:
#Test
public void testGetDisplayName()
{
EasyMock.expect(mockMessageResourse.getMessage("ClassB.title")).andReturn("someTitle");
EasyMock.replay(mockMessageResourse);
clientMessages = new ClientMessages(mockMessageResourse);
classToTest = new ClassB();
Assert.assertEquals("someTitle" , classToTest.getDisplayName());
}
For me, this exception was occurring because the method I was trying to stub was final (something I hadn't realized).
If you want to stub a final method you'll need to use Powermock.

Categories