How to mock final field? mockito/powermock - unit-testing

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

Related

Should I initialize mock objects in setup or in the test case?

In unit testing with help of mock/fake objects, I wonder whether it's more preferable to initialize the mocks in SetUp or in the test method itself, if my test class contains methods that test the same class (and thus, fake object needed should be the same for all test case). Something like this:
class FooTests
{
Mock<IBar> mockBar;
Foo fooUnderTest;
[SetUp]
public void Setup()
{
mockBar = new Mock<IBar>();
fooUnderTest = new fooUnderTest(mockBar.Object);
}
[Test]
public void MyTest()
{
//setup mock methods
mockBar.SetUp( ... )
//test
fooUnderTest.TestSomething()
//assert something here
}
}
It seems that this will prevent us from duplicating code to mockBar and fooUnderTest in each test case, but the downside is that I have to declare class variables mockBar and fooUnderTest (or is this really a downside?), and it will be problematic if I want to have some special setup (for example, if in some testcase I want to overriede some of the virtual methods of Foo). Any suggestion what is the best practice?
If there is some common setup shared by all tests in a suite/fixture (including setting up some expectations on mock collaborators), MOVE to a Setup method. (Ditto for incidental details that are not relevant to the reader within the test)
If one test case wants to extend common setup, add the specific setup inline within test-case itself
If one test case wants a different setup (inspite of significant overlap), MOVE to different test suite and figure out some other mechanism to share setup (e.g. via composition, utility methods, Object Mothers, etc.)

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);

Unit Testing using Mockito or JMock

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.

JUnit 4 base functionality

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.

How do I unit test and mock a static extension method with Rhino Mocks?

I have following extension method written:
static public IQueryable<OutboundPattern> ByClientID(this IQueryable<OutboundPattern> qry, int clientID)
{
return from p in qry
where p.ClientID == clientID
select p;
}
I also have the following service layer method written:
public IList<OutboundPattern> OutboundPatterns(int ClientId)
{
return _outboundpatternRepository.OutboundPatterns().ByClientID(ClientId).ToList();
}
I would love to know how to mock with Rhino mocks? I know that static methods and Rhino mocks are no good together? It can not mock statics methods.
Daniel Cazzulino has a couple of blog posts that describe an approach to mocking static extension methods.
The basic idea is that you take all the static extension methods... and move them to an interface, which can be easily mocked, and make the static class use a factory to construct instances of that interface. This factory can be replaced by a friend test assembly for mocking purposes.
This might be more work/change than you would like to make in this case, but it's the only way to do it that I've seen (besides buying TypeMock).
Here are his posts:
Making extension methods amenable to mocking
How to mock extension methods
I don't think you can mock extension methods - because they are effectively static methods. In terms of testing you should think about them more as a part of the class that uses them rather than the class on which they are defined (similar to helper methods). As a result I usually use extension methods to do some simple transformation and avoid business logic in them.
What is the class under test at this point?
Assuming it is OutboundPatterns, then I'd mock _outboundpatternRepository to return something (a simple list maybe) that only had clients that matched the requested ClientId and maybe again when it is empty. Separate unit tests should be written for the extension method.
So to recap, I'd test OutboundPatterns by letting it call the real ByClientID but with strictly controlled data.