I'm writing a junit test for a particular method. The method contains calls to other methods in a DAO class which I am mocking with EasyMock.
I want to assert that one of these DAO class methods is called once, which is what I assume expectLastCall().once() is for. The method in question returns void.
The test I have currently passes, I just want to make sure my logic is correct as I haven't used EasyMock before. I used this question as a reference: EasyMock expectations with void methods
So, here is the code:
#Before
public void setUp() throws Exception{
this.fooService = new FooService();
this.fooMock = createStrictMock(FooDAO.class);
}
#Test
public void test_fooTest(){
String arg1 = "arg1";
String arg2 = "arg2";
this.fooService.setFooDAO(fooMock);
expect(this.fooMock.someMethod(arg1, arg2)).andReturn(something);
fooMock.methodThatShouldBeCalledOnce(EasyMock.<Object>anyObject());
EasyMock.expectLastCall().once();
replay(this.fooMock);
this.fooService.methodUnderTest(someArg, someArg2);
verify(this.fooMock);
}
What I think this does is assert that there is a call to methodThatShouldBeCalledOnce and that it only happens once. I don't really care about someMethod but of course EasyMock complains if it's not told to expect it.
Thank you!
That looks correct to me. You could easily check by yourself by removing the call to the void method and verify that the test fails, or by adding a second call to the void method and see that the test also fails.
If you don't care about some methods, you should create a nice mock. Then, indeed, there's no need to call expectLastCall. It is implicit but can be a good practice to make it obvious you are mocking a method. once() is also not needed since it is the default.
So, if a rephrase it, using a nice mick, removing implicit calls, adding static imports and not adding redundant "this", you should get:
#Before
public void setUp() throws Exception{
fooService = new FooService();
fooMock = createNiceMock(FooDAO.class);
fooService.setFooDAO(fooMock);
}
#Test
public void test_fooTest(){
fooMock.methodThatShouldBeCalledOnce(anyObject());
replay(fooMock); // or replayAll() if you extend EasyMockSupport
fooService.methodUnderTest(someArg, someArg2);
verify(fooMock); // or verifyAll() if you extend EasyMockSupport
}
Related
I am investigating using mocking for unit tests I'm adding to existing code. For this I'm using HippoMocks. This involves another class calling some methods on my mock (that are all virtual). I want to avoid overspecifying all this but HippoMocks keep throwing NotImplementedException whenever the other class calls functions on my mock that I have not specified.
The below code exposes my issue.
void test()
{
class SimpleClassToMock
{
public:
virtual void memberFunction1() {}
virtual void memberFunction2() {}
};
MockRepository mocks;
// true or false here makes no difference.
mocks.autoExpect = true;
SimpleClassToMock* m = mocks.Mock<SimpleClassToMock>();
// I care about this function getting called.
mocks.ExpectCall(m, SimpleClassToMock::memberFunction1);
m->memberFunction1();
// HippoMocks fails on the next line by throwing NotImplementedException.
m->memberFunction2();
}
Is there any way to tell HippoMocks not to fail here? I only want to specify the expectations for things I care about for a particular test, not every single thing that is called.
PS: To those that have mocking experience, am I thinking about this all wrong? Is overspecifying the test in cases such as this not a problem/"what you want"?
To avoid overspecifying, you can use OnCall to allow them to be called 0-N times (optionally with argument checks, order checks and so on).
I want to test if a method has been called in the test.
My problem is that when I want to create the expectations it is not working as I thought. The next line actually runs the method, not only create an expectation:
Expect.Call(() => mockedService.MethodThatIExpectToRun(params));
There is another way:
mockedService.Expect((s=> s.MethodThatIExpectToRun(params)));
But this also actually runs the method, not only creates an expectation to be fulfilled by the test.
And this line that asserts if the method was not called also actually calls the method, not only checks whether it was called.
mockedService.AssertWasCalled(s=> s.MethodThatIExpectToRun((params)));
additional info:
MethodThatIExpectToRun returns void
For prgmtc's comment:
IService mockedService = MockRepository.GeneratePartialMock<Service>(mockedRepository_1, ..., mockedRepository_n);
Usually when you have PartialMock that's calling the real method when setting a Stub or Expect, it means the virtual keyword is missing on the method.
Make sure Service.MethodThatIExpectToRun is virtual.
A more general (although perhaps less useful) remark: Partial mocks can point to a design smell of the code under test. If you only want to provide expectations for a part of a class, then perhaps that class has too many responsibilities and should be split into multiple classes? That way you can cleanly isolate responsibilities/collaborators and have no need for the partialmock construct. If you mock (not partial mock) an interface or virtual member of a concrete class the call won't go through to the real implementation.
For example:
Console.WriteLine("Real object: ");
new Foo().Bar();
Console.WriteLine("Mocked object: ");
var aFoo = MockRepository.GenerateMock<Foo>();
aFoo.Expect(f => f.Bar());
aFoo.Bar();
...
public class Foo
{
public virtual void Bar()
{
Console.WriteLine("REAL IMPLEMENTATION");
}
}
Outputs:
Real object:
REAL IMPLEMENTATION
Mocked object:
I am using Easymock with junit for writing my unit tests. I have a doubt in this regard and I could not find a very lucid explanation regarding it.
How do you test void methods ?
Since they do not return anything, so something like :
Easymock.expect(myMockObject.func(easymock.isa(String.class))).andReturn("NOTHING TO RETURN HERE");
above would not work as I have nothing to return.
So, how do I set my expectation and how to test a void method ?
I came to know that something like easymock.expectLastCall() would fit in but I am not sure as to what it does and why do we need it.
A lucid explanation would be highly appreciated.
First with easymock you aren't testing the method that you want to test, you are mocking the methods it calls.
For example:
public void doSomething(){
i = otherObject.foo();
otherObject.bar();
}
The method doSomething(), is the method you wanted to test. i is a member variable of your class, let's say an integer. The calls otherObject.foo() and otherObject.bar() are method calls on another object that could be mocked (Mayby they are hard to set up, and you just want to mock them...). Now suppose that bar() is a void method, then for otherObject.foo() you could setup a normal expect, but for bar() you will need expectLastCall().
When you test a void method (doSomething()), you want to check it's side effects... Did it change the collection? Did it create a new Object? Or, in this example, did the value of i change?
What is the proper way with JUnit 4 to create test cases to use common functionality: e.g. setup that is common to several unit test classes? What I did was create a test case and put the common functionality in the #Before method, then any test case that needs this would extend the base class. However, this seems to require doing: super.setUp() in every subclass.
Is there a better way?
EDIT
Actually my proposed solution is not working. Sometimes JUnit will call the base class TWICE. Once if it happens to run the test on the base class first, and again when it reaches a child class (at least I think this is whats happening). So a better way of "inheriting" common test case functionality would be great.
You don't need to invoker super.setup() if you use the #Before annotation:
When writing tests, it is common to find that several tests need
similar objects created before they
can run. Annotating a public void
method with #Before causes that method
to be run before the Test method. The
#Before methods of superclasses will
be run before those of the current
class.
I'd suggest something like this:
#Before
public void initForAll() {}
In the super/Main class
and any
#Before
public void initTest() {...}
In your Testcases.
EDIT:
To answer your questions in the edit.
You could use #BeforeClass which will be invoked once per TestClass.
But I Think you are looking for something like a lazy /static Initialisation.
I do this like this:
private boolean initialized = false;
#BeforeClass
public static void init()
{
if(initialized)
{
return;
}
//Initialize everything
initialized = true;
}
thats a pretty good way to do it. If you have a setUp() on the subclass, then yes, you have to invoke super.setUp(), but really, how hard is that?
Have you tried other approach.
Instead of creating a base class with a common functionality, make an util class with static methods which will the common functionality. Then just call util methods in #Before annotated method of each test case.
If your base class has a method public void setUp(), and so does your sub-class, then the sub-class's setUp method overrides the base class's method of the same name and signature, so only the sub-class's method will be called (and it may be called when the base class's method should have been called; not sure about this).
The solution is to call your base class setup method something else, e.g. baseSetup(). Then they will both be called automatically. Joachim's answer does address the naming, but I wanted to be clearer about the effects of method override.
Say I have an interface IFoo which I am mocking. There are 3 methods on this interface. I need to test that the system under test calls at least one of the three methods. I don't care how many times, or with what arguments it does call, but the case where it ignores all the methods and does not touch the IFoo mock is the failure case.
I've been looking through the Expect.Call documentation but can't see an easy way to do it.
Any ideas?
You can give rhino mocks a lambda to run when a function get's called. This lambda can then increment a counter. Assert the counter > 1 and you're done.
Commented by Don Kirkby:
I believe Mendelt is referring to the Do method.
Not sure this answers your question but I've found that if I need to do anything like that with Rhino (or any similiar framework/library), anything that I didn't know how to do upfront, then I'm better just creating a manual mock.
Creating a class that implements the interface and sets a public boolean field to true if any of the methods is called will be trivially easy, you can give the class a descriptive name which means that (most importantly) the next person viewing the code will immediately understand it.
If I understood you correctly you want to check that the interface is called at least once on any of three specified methods. Looking through the quick reference I don't think you can do that in Rhino Mocks.
Intuitively I think you're trying to write a test that is brittle, which is a bad thing. This implies incomplete specification of the class under test. I urge you to think the design through so that the class under test and the test can have a known behavior.
However, to be useful with an example, you could always do it like this (but don't).
[TestFixture]
public class MyTest {
// The mocked interface
public class MockedInterface implements MyInterface {
int counter = 0;
public method1() { counter++; }
public method2() { counter++; }
public method3() { counter++; }
}
// The actual test, I assume you have the ClassUnderTest
// inject the interface through the constructor and
// the methodToTest calls either of the three methods on
// the interface.
[TestMethod]
public void testCallingAnyOfTheThreeMethods() {
MockedInterface mockery = new MockedInterface();
ClassUnderTest classToTest = new ClassUnderTest(mockery);
classToTest.methodToTest();
Assert.That(mockery.counter, Is.GreaterThan(1));
}
}
(Somebody check my code, I've written this from my head now and haven't written a C# stuff for about a year now)
I'm interested to know why you're doing this though.