I am replacing PowerMock with JMockit in old unit testing case.
Below is the PowerMock sample code which mock the File.class constructors with any argument .
Can JMockit mock constructors with any argument like it ?
The situation is this:myFile is a mock. And I want to simulate returning myFile when calling any constructor in the File class..So What is the code like.
// PowerMock
whenNew(File.class).withAnyArguments().thenReturn(myfile);
// JMockit
new Expectations() {{
new File(anyString);
result = myfile;
minTimes = 0;
}};
Related
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
In my gtest framework, I mocked a few functions and written some testcases. And I see that I used the same mock functions over and over with EXPECT_CALL in many testcases. So, I am just wondering if I can place these common mock EXPECT_CALL's in one place and simply call them, so the number of lines become less and the testcase looks simpler.
I tried putting them in one function and tried to call the function but it gave me many compile issues. Any one has any idea?
From Google Mock doc relative to GTest, it is not possible to delegate to a function the EXPECT_CALL macro.
More precisely,
Important note: Google Mock requires expectations to be set before the
mock functions are called, otherwise the behavior is undefined. In
particular, you mustn't interleave EXPECT_CALL()s and calls to the
mock functions.
The EXPECT calls need to be inside a test case or a test fixture. You can achieve the result you want using a test fixture.
class MyTest : public ::testing::test
{
MyTest // can use ctor
{
EXPECT_CALL(mock, ...);
}
SetupA() // or can use a member function
{
EXPECT_CALL(mock, ...);
EXPECT_CALL(mock, ...);
}
MockObject mock;
};
TEST_F(MyTest, TestOne)
{
EXPECT_CALL(mock, ...);
// do something - two expectations are set
}
TEST_F(MyTest, TestTwo)
{
SetupA();
// do something - three expectations are set
}
Is there any good feature in EasyMock that is not there or not properly handled (as compared to EasyMock) in Mockito?
I would like to know about some feature like for eg. Mockito supports easy injection of all mocks into the Class Under Test by using the # InjectMocks, which is not the case in EasyMock (out of the box). Similarly are there any features in EasyMock which are either not there or not handled as good as in EasyMock?
One feature that comes to mind is the support for implicitly verified expectations, which Mockito lacks:
#Test
public void usingEasyMock()
{
Collaborator mock = createMock(Collaborator.class);
expect(mock.registerXyz("xyz")).andReturn(true);
replay(mock);
new ClassUnderTest().doSomething(mock);
verify(mock);
}
#Test
public void usingMockito()
{
Collaborator mock = mock(Collaborator.class);
when(mock.registerXyz("xyz")).thenReturn(true);
new ClassUnderTest().doSomething(mock);
verify(mock).registerXyz("xyz");
}
Note the duplicate invocation to registerXyz("xyz") in the second test. Mockito could perhaps add a times(n) method to be used together with calls to thenReturn(...) (which EasyMock has). This would avoid having to duplicate code in situations like this.
I'm trying to follow Roy Osherove's UnitTests naming convention, with the naming template: [MethodName_StateUnderTest_ExpectedBehavior].
Following this pattern. How would you name a test calling a constructor?
[Test]
public void ????()
{
var product = new Product();
Assert.That(product, Is.Not.Null);
}
Constructor_WithoutArguments_Succeeds
I don't know how you would call this unit test but I strongly suggest you avoid writing it as there's nothing on earth to make the assert fail. If the constructor succeeds the CLR guarantees you a fresh instance which won't be null.
Now if the constructor of your object throws an exception under some circumstances you could name it like this:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Product_Constructor_ShouldThrowIfNullArgumentSupplied()
{
new Product(null);
}
So two possible cases for the code you are testing:
You get an instance
You get an exception
No need to test the first.
I have just crafted the following test using Rhino mocks. Does my test look valid and make sense to those more experienced with mocking?
I am a a little confused that I haven't had to use the DynamicMock() or StrictMock() methods to create a seemingly valid test.
This test tests that the Add method was invoked on the supplied ICachingStrategy with the supplied parameters.
object o = new object();
DateTime d = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 0, 0, 0);
CacheStorageStyle s = CacheStorageStyle.Unmodified;
string f = "test";
//arrange
var stubStrategy = MockRepository.GenerateStub<ICachingStrategy>();
var stubEncoder = MockRepository.GenerateStub<ICacheItemEncoder>();
stubStrategy.Stub(x => x.Add(o,d,s,f)).Return("test:key");
stubEncoder.Stub(x => x.Encode(o,s)).Return(o);
_mocks.ReplayAll();
//act
ICache c = new Cache(stubStrategy, stubEncoder);
c.Add(o, d, s, f);
//assert
stubStrategy.AssertWasCalled(x => x.Add(o,d,s,f));
The question is: does it succeed? Do you expect it to? If the answers are yes and yes, then the test is good. You can further test the test by forcing it to fail by commening out the call to Add() in your implementation. If the Add() method is not called, the test should fail.
Here is the relevant documentation that explains the difference between stubs and mocks. The essential difference is that stubs "will never cause a test to fail." They are there just to make the testing code work. The documentation further recommends that stubs should be preferred over mocks wherever possible.
Your test appears valid to me because you are primarily interested in whether the Add() method was called, and you are explicitly asserting for that call. You're not testing the other method calls, so you're stubbing them instead of mocking them.
re: Strict vs Dynamic - another things thats worth noting is that in RhinoMocks 3.5 a call to MockRepository.GenerateMock() will not generate a strict mock.
Depending on what your testing you may/may not care what was/wasn't called on your mock.