Unit Testing using Mockito or JMock - unit-testing

Unit Testing:
I have the following classes
public class BImpl extends AImpl
{
public BImpl(final C c)
{
super(c);
}
public String getInfo()
{
final String info = getInformation();
// Do all my logic here
return info;
}
}
public abstract class AImpl
{
public String getInformation()
{
// some logic...returns String.
}
}
I am trying to unit test the method getInfo() by using any of the mocking methods available either Mockito or JMock.
for example when using Mockito I am using this way:
final AImpl aImpl = mock(AImpl.class);
when(aImpl.getInformation()).thenReturn("ABC");
Now since I have to create an instance of BImpl the only way I can create is using the constructor available.
final BImpl bImpl = new BImpl (C);
bImpl.getInfo();
when it calls into the getInfo() method and it tries to call getInformation(), it isn't calling the mocked object but calling the actual one.
What is the good way to test this method.
Is there any other way I can create an instance of BImpl without going by the constructor that I have given above?
Thanks!!

IMHO it's not a problem with mocking libraries but with your design. You want to test getInfo() method by mocking getInformation() on which it depends. Unit testing a method mocking all its dependencies is a right way to go and all mocking frameworks support it pretty well. So why you experience these problems?
Because you have chosen inheritance where composition was actually needed. You are abusing inheritance to implement uses relationship, whereas it should have been composition. Inheriting from a class just to have a convenient access to its methods is asking for trouble. Think of extending EntityManager by every repository/DAO...
You should refactor your code first so that BImpl has AImpl and the latter one is injected somehow. Then you can let some DI framework to perform the injection in production code (or do it yourself) with real implementation while injecting mock in unit test.

Related

Writing unit tests which may access private/protectedstate

I use Boost Test for unit tests. I typically have a fixture struct:
class ClassBeingTested
{
protected:
int _x; // Want to access this directly in my unit tests
};
struct TestFixture : public ClassBeingTested
{
// I can access ClassBeingTested::_x here but it means i have to add getters for each test to call
ClassBeingTested _bla;
};
However, even if my fixture inherits from ClassBeingTested or uses a friend relationship I cannot access private/protected methods/state from each individual test:
BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
_bla.doSomething();
BOOST_REQUIRE_EQUAL(_bla.x, 10); // Compiler error. I cannot access ClassBeingTested::_x here
}
only the fixture, which means I have to add a new getter (or test) for each access I wish to make.
Is there any way to achieve this? I have to add public getter methods to ClassBeingTested which are only used by tests, which isn't ideal.
(Please no replies of 'test using the public interface', that's not always possible).
You can make a friend test buddy, struct ClassBeingTestedBuddy; with friend struct ClassBeingTestedBuddy; in the class ClassBeingTested.
Have the test buddy class expose all the protected or private variables or methods that you need for all your tests.
It'd look like...
struct ClassBeingTestedBuddy {
ClassBeingTested* obj;
ClassBeingTestedBuddy(ClassBeingTested* obj_)
: obj{obj_} {}
};
...plus anything else you'd want to expose.
This is but one way of allowing the tests a bridge to the protected and private data and methods. But since it is all code in your project, for your testing use, it is a reasonable way of getting the test code access without too much instrumenting your actual code.

Unit Testing with Rhino Mocks

I have the following method called Execute() from the Abstract class called AutoLetterGenBatch in my ConsoleApp. I am trying to unit test this.
public void Execute()
{
BatchJobSecurity.Instance.CreatePrincipal();
DoExecute();
}
So I set up what I believe are all the proper references and try to invoke the method like below .
[TestMethod]
public void TestMethod1()
{
AutoLetterGenBatchJob ALGBJ = new AutoLetterGenBatchJob();
ALGBJ.Execute();
}
However, when I go to do the build it gives me this compilation error Error 34 Cannot create an instance of the abstract class or interface 'AutoLetterGenBatch.AutoLetterGenBatchJob' .
I am somewhat new to unit testing. I realize this probably isn't much of a test but I just want to see my Execute() method get hit for the time being. I have read that a good way to get around this problem with abstract classes is to set up a mock object for the abstract class. So I try to do this with RhinoMocks.
[TestMethod]
public void TestMethod1()
{
AutoLetterGenBatchJob ALGBJ = MockRepository.GenerateStub<AutoLetterGenBatchJob>();
ALGBJ.Execute();
}
It now builds with all of the proper using statements in place. However when the test runs I now get this error. Can't find a constructor with matching arguments . Again I am pretty new to this. If someone can help me to understand what it is I need to do it would be appreciated.
YOur first test doesn't make any sense, your class is abstract, by definition you can't create an instance of it. In order to test that method you need a class which derives from AutoLetterGenBatch and you then create an instance of this class and do what is neccessary to invoke the method on this instance.
Using a mocking framework would be one way, as would creating a test class of your own. Personally I would go with the 'roll your own' at first as this will be easier to debug.
public class TestAutoLetterGenBatch : AutoLetterGenBatch
{
}
once you have this class you'll see that you need to call the constructor that AutoLetterGenBatch declares. This is the same issue that rhino mocks it complaining about. Without seeing the class AutoLetterGenBatch we can't advise any further.
For what it is worth, Rhino mocks has seen little work recently and you would probably be better using Moq or another more active framework.
Also you need to generate a partial mock to do the testing you want to do, no a stub.

How to mock final field? mockito/powermock

I have same class
class MyCalss{
final static SomeClass field = new SomeClass();
...
}
I should to mock instance of MyCalss. This mock should contain field like real object.
How can I achieve it?
Mocking operates on methods and interfaces, not fields; furthermore, it operates on instance members, not static members. Mockito and Powermock are not the right tools to solve this problem.
Though you can use reflection to set final fields, you're effectively working around your own declaration, and are subject to the limitations and hazards of JLS 17.5.3.
A better design would be to rewrite the method in the system under test to inject its SomeClass dependency:
public void methodUnderTest() {
methodUnderTest(MyClass.field);
}
/** Package-visible for testing. Test this method instead. */
void methodUnderTest(SomeClass someClass) {
someClass.firePhotonTorpedoes();
}
You can use a framework that allows for mocking calls to constructors such as JMockit or Powermock.
Powermock
JMockit

What do you call an inner class used for testing?

Our team has members who are just ramping up on unit testing and we're struggling with some terminology. I'd like to determine a name for a particular pattern. I'm hoping there's one that's already embraced by other developers, but if not, I'd like to come up with one that's descriptive and will make talking about test strategies easier.
This pattern is used quite a bit for testing abstract methods, but is also handy when an object creates a new object (for cases where DI doesn't work or isn't desired). The basic pattern is to use an inner class that extends the class under test to expose protected methods.
Consider the following code (which is pseudocode, based on Java, but should translate to most languages):
The class to test:
public class MyClass {
public void send() {
//do something
}
protected MailMessage createNewMailMessage() {
return new MailMessage();
}
}
The test:
public class MyClassTest {
private MyClass myClass = new TestableMyClass();
private MailMessage mockMessage = mock(MailMessage.class);
public void setup() {
((TestableMyClass)myClass).setMailMessage(mockMessage);
}
// Do some tests //
private class TestableMyClass extends MyClass {
private MailMessage mailMessage;
public void setMailMessage(MailMessage mailMessage) {
this.mailMessage = mailMessage;
}
protected MailMessage createNewMailMessage() {
return mailMessage;
}
}
}
So, what do you call this pattern? TestableMyClass a "Mock" object, but since it's not managed by a mocking framework, it seems like there should be another term to describe this pattern. Any suggestions or ideas?
I'd call it a stub. As you said, it's not a true "mock", since its behavior isn't being controlled by a mocking framework, but is a "true" object.
You don't need to use a mocking framework to call something a Mock/Stub object - your MyClassTest (which I'm assuming is supposed to extend MyClass) is just a Stub.
I don't think there's a particular name for the case where Mocks/Stubs are defined as inner classes of your test class - and in the particular example here, there's no reason for it to be an inner class - it could just be a package protected class (in the same file as MyClassTest or in its separate file..)
Mock contains test assertions.
Stub provides simple hard-coded values to make the test work.
Fake provides complex behavior/answers.
I usually add two underscores prefixing the inner class for testing so it doesn't show up in auto-complete, e.g. '__TestableMyClass'. Also if you are using Mockito you should be stubbing like so
MyClass myClass = mock(MyClass.class);
when(myClass.createNewMailMessage()).thenReturn(mockMessage);

Rhino Mocks - How can I test that at least one of a group of methods is called?

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.