Mockito verify state halfway through test - mockito

I have some code that put simply, sets an object to a state of PROCESSING, does some stuff, then sets it to SUCCESS. I want to verify that the PROCESSING save is done with the correct values.
The problem is when the verify() tests are performed, .equals() is called on the object as it is at the end of the test, rather than halfway through.
For example the code:
public void process(Thing thing) {
thing.setValue(17);
thing.setStatus(Status.PROCESSING);
dao.save(thing);
doSomeMajorProcessing(thing);
thing.setStatus(Status.SUCCESS);
dao.save(thing);
}
I want to test:
public void test() {
Thing actual = new Thing();
processor.process(actual);
Thing expected = new Thing();
expected.setValue(17);
expected.setStatus(Status.PROCESSING);
verify(dao).save(expected);
// ....
expected.setStatus(Status.SUCCESS);
verify(dao).save(expected);
}
On the first verify, actual.getStatus() is Status.SUCCESS, as Mockito just keeps a reference to the object and can only test it's value at the end.
I have considered that if a when(...) where involved then .equals() would be called at the correct time and the result would only happen if Thing was what I wanted it to be. However, in this case .save() returns nothing.
How can I verify that the object is put into the correct states?

Ok, I found a solution, but it's pretty horrible. Verify is no good to me because it runs too late, and stubbing is hard because the method returns a void.
But what I can do is stub and throw an exception if anything but the expected is called, while validating that something is called:
public void test() {
Thing actual = new Thing();
Thing expected = new Thing();
expected.setValue(17);
expected.setStatus(Status.PROCESSING);
doThrow(new RuntimeException("save called with wrong object"))
.when(dao).saveOne(not(expected));
processor.process(actual);
verify(dao).saveOne(any(Thing.class));
// ....
expected.setStatus(Status.SUCCESS);
verify(dao).saveTwo(expected);
}
private <T> T not(final T p) {
return argThat(new ArgumentMatcher<T>() {
#Override
public boolean matches(Object arg) {
return !arg.equals(p);
}
});
}
This infers that expected is called. Only drawback is that it'll be difficult to verify the method twice, but luckily in my case both DAO calls are to different methods, so I can verify them separately.

Why not just mock the Thing itself and verify that? eg:
public class ProcessorTest {
#Mock
private Dao mockDao;
#InjectMocks
private Processor processor;
#BeforeMethod
public void beforeMethod() {
initMocks(this);
}
public void test() {
Thing mockThing = Mockito.mock(Thing.class);
processor.process(thing);
verify(mockThing).setStatus(Status.PROCESSING);
verify(mockThing).setValue(17);
verify(mockDao).save(mockThing);
verify(mockThing).setStatus(Status.SUCCESS);
}
If you want to explicitly test the order in which these things happen, use an InOrder object:
public void inOrderTest() {
Thing mockThing = Mockito.mock(Thing.class);
InOrder inOrder = Mockito.inOrder(mockThing, mockDao);
processor.process(mockThing);
inorder.verify(mockThing).setStatus(Status.PROCESSING);
inorder.verify(mockThing).setValue(17);
inorder.verify(mockDao).save(mockThing);
inorder.verify(mockThing).setStatus(Status.SUCCESS);
inorder.verify(mockDao).save(mockThing);
}

Mockito has a problem verifying mutable objects. There is an open issue about this (http://code.google.com/p/mockito/issues/detail?id=126)
Maybe you should switch to EasyMock. They use a record/playback pattern and do the verification at the time of the call in contrary to Mockito, where the verification happens after the call.
This Mockito version of the test has the mentioned problem:
#Test
public void testMockito() {
Processor processor = new Processor();
Dao dao = Mockito.mock(Dao.class);
processor.setDao(dao);
Thing actual = new Thing();
actual.setValue(17);
processor.process(actual);
Thing expected1 = new Thing();
expected1.setValue(17);
expected1.setStatus(Status.PROCESSING);
verify(dao).save(expected1);
Thing expected2 = new Thing();
expected2.setValue(19);
expected2.setStatus(Status.SUCCESS);
verify(dao).save(expected2);
}
This EasyMock version works fine:
#Test
public void testEasymock() {
Processor processor = new Processor();
Dao dao = EasyMock.createStrictMock(Dao.class);
processor.setDao(dao);
Thing expected1 = new Thing();
expected1.setValue(17);
expected1.setStatus(Status.PROCESSING);
dao.save(expected1);
Thing expected2 = new Thing();
expected2.setValue(19);
expected2.setStatus(Status.SUCCESS);
dao.save(expected2);
EasyMock.replay(dao);
Thing actual = new Thing();
actual.setValue(17);
processor.process(actual);
EasyMock.verify(dao);
}
In my example doSomeMajorProcessing sets value to 19.
private void doSomeMajorProcessing(Thing thing) {
thing.setValue(19);
}

After reviewing https://code.google.com/archive/p/mockito/issues/126
I was able to get my version of this working (Java 15, Mockito 3.6.28):
// ========= CODE ==========
public void process(Thing thing) {
thing.setValue(17);
thing.setStatus(Status.PROCESSING);
dao.save(thing);
doSomeMajorProcessing(thing);
thing.setStatus(Status.SUCCESS);
dao.save(thing);
}
// ========= TEST ==========
// ++++++ NOTE - put this at class level
private final Dao dao = mock(Dao.class, withSettings().defaultAnswer(new ClonesArguments()));
public void test() {
Thing actual = new Thing();
processor.process(actual);
ArgumentCaptor<Thing> captor = ArgumentCaptor.for(Thing.class);
verify(dao, times(2)).save(captor.capture());
List<Things> savedCalls = captor.getAllValues();
assertEquals(Status.PROCESSING, savedCalls.get(0).getStatus());
assertEquals(Status.SUCCESS, savedCalls.get(1).getStatus());
}

Using argThat with a hamcrest Matcher should do the trick. The Matcher would match its passed thing if the thing has the PROCESSING status:
public class ProcessingMatcher extends BaseMatcher<Thing> {
#Override
public boolean matches(Object item) {
if (item instanceof Thing) {
return ((Thing) item).getStatus() == Status.PROCESSING;
}
return false;
}
#Override
public void describeTo(Description description) {
description.appendText(" has the PROCESSING status");
}
}
And then in your test, use the following code :
public class MyTest {
public void test() {
//...
mockDao.save(argThat(hasTheProcessingStatus()));
}
static ProcessingMatcher hasTheProcessingStatus() {
return new ProcessingMatcher();
}
}

Related

Mockito: How to test a class's void method?

Unit test noob here.
I have three classes: Db1Dao, Db2Dao, ExecuteClass where Db1Dao, Db2Dao are database access objects for two different databases. My goal is to fetch some data from db1 using Db1Dao and run executeClass.execute() to "put" the processed data into db2 using Db2Dao.
My ExecuteClass looks like this:
class ExecuteClass {
private Db1Dao db1Dao;
private Db2Dao db2Dao;
public void execute() {
...
List<String> listOfString = getExternalData(someParam);
List<Metadata> metadatum = db1Dao.get(someInputs);
... I do something to generate a list of new class `A` based on listOfString & metadatum ...
try {
db2Dao.put(listOfA);
} catch (PutException e){
...
}
}
public List<String> getExternalData(SomeClass someParam){
... do something
return listOfString;
}
}
Now I want to test:
Given a specific listOfString (returned by getExternalData) and a specific metadatum (returned by db1Dao.get):
Will I get the desired listOfA?
Am I able to call db2Dao.put and its input parameter is listOfA?
Particularly, I have hard-coded sample listOfString and metadatum and desired listOfA (and they will be passed via an object MockData, see the following code) but I don't know how to write the test using Mockito. The following is a test class I wrote but it does not work:
class TestClass extends BaseTest {
#Mock
private Db1Dao db1Dao;
#Mock
private Db2Dao db2Dao;
private ExecuteClass executeClass;
#BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
executeClass = new ExecuteClass(db1Dao, db2Dao);
}
#ParameterizedTest
#MethodSource("MockDataProvider")
public void executeClassTest(final MockData mockData) throws PutException {
Mockito.when(db1Dao.get(Mockito.any(), ...))
.thenReturn(mockData.getMetadatum());
ExecuteClass executeClassSpy = Mockito.spy(executeClass);
Mockito.when(executeClassSpy.getExternalData(Mockito.any()))
.thenReturn(mockData.getListOfString());
executeClassSpy.execute();
// executeClass.execute(); not working neither...
List<A> listOfA = mockData.getDesiredListOfA();
Mockito.verify(db2Dao).put(listOfA);
}
}
Could anyone please let me know? Thank you in advance!!
You should not create a spy of the same class you want to test. Instead, try to write a unit test for the smallest amount of code (e.g. a public method) and mock every external operator (in your case Db1Dao and Db2Dao).
If testing a public method involves calling another public method of the same class, make sure to mock everything inside the other public method (in your case getExternalData). Otherwise, this other public method might be a good candidate for an extra class to have clear separation of concerns.
So, remove the ExecuteClass executeClassSpy = Mockito.spy(executeClass); and make sure you setup everything with Mockito what's called within getExternalData.
To now actually, verify that Db2Dao was called with the correct parameter, either use your current approach with verifying the payload. But here it's important to 100% create the same data structure you get while executing your application code.
Another solution would be to use Mockito's #Captor. This allows you to capture the value of why verifying the invocation of a mock. Later on, you can also write assertions on the captured value:
#Captor
private ArgumentCaptor<ClassOfListOfA> argumentCaptor;
#Test
public void yourTest() {
Mockito.verify(db2Dao).put(argumentCaptor.capture());
assertEquals("StringValue", argumentCaptur.getValue().getWhateverGetterYouHave);
}
The following code worked for me.
I partially accepted #rieckpil's answer. I used #Captor which is very handy.
The reason I had to mock getExternalData() is because its implementation is still a "TODO".
class TestClass extends BaseTest {
#Mock
private Db1Dao db1Dao;
#Mock
private Db2Dao db2Dao;
#Captor
private ArgumentCaptor<List<A>> argumentCaptor;
private ExecuteClass executeClass;
#BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
executeClass = new ExecuteClass(db1Dao, db2Dao);
}
#ParameterizedTest
#MethodSource("MockDataProvider")
public void executeClassTest(final MockData mockData) throws PutException {
Mockito.when(db1Dao.get(Mockito.any(), ...))
.thenReturn(mockData.getMetadatum());
ExecuteClass executeClassSpy = Mockito.spy(executeClass);
Mockito.when(executeClassSpy.getExternalData(Mockito.any()))
.thenReturn(mockData.getListOfString());
executeClassSpy.execute();
List<A> listOfA = mockData.getDesiredListOfA();
Mockito.verify(db2Dao).put(argumentCaptor.capture());
assertEquals(listOfA, argumentCaptor.getValue());
}
}

How to mock a object construction that is created using reflection i.e newInstance() method

I have a piece of code below where Employee class creates object of AppraisalCalculator using reflection. I want to mock this AppraisalCalculator object using PowerMockito.
class AppraisalCalculator {
public int appraisal() {
return 300;
}
}
class Employee {
public int updateSalary() {
// line 1
AppraisalCalculator ac =
AppraisalCalculator.class.getConstructor().newInstance();
return ac.appraisal();
}
}
class TestRunner {
#Test
public void test() {
AppraisalCalulator acMock=PowerMockito.mock(AppraisalCalculator.class);
PowerMockito
.whenNew(AppraisalCalculator.class)
.withNoArguments()
.thenReturn(600);
Employee emp = new Employee();
int actualValue = emp.updateSalary();
int expectedValue=600;
Assert.equals(expectedValue,actualValue);
}
}
Here, even though I have mocked the Appraisal calculator object, it still calls the real appraisal() method from AppraisalCalculator. If the actual AppraisalCalculator at line 1 is created using new Operator instead of newInstance() then this mocking works.
Can anyone explain why this is not working if the actual object is created using reflection? What can I do to mock this Object in such scenario?
Let me first start by rephrasing your question will fully working code.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Employee.class)
public class TestRunner {
#Test
public void test() throws Exception {
AppraisalCalculator acMock = PowerMockito.mock(AppraisalCalculator.class);
PowerMockito
.whenNew(AppraisalCalculator.class)
.withNoArguments()
.thenReturn(acMock);
when(acMock.appraisal()).thenReturn(600);
Employee emp = new Employee();
int actualValue = emp.updateSalary();
int expectedValue = 600;
assertEquals(expectedValue, actualValue);
}
}
Then, the way PowerMock works is that the PowerMockRunner will look at each class that needs to be prepared (here Employee), then look for a call to the constructor we want to replace and do it. This is done at class loading. The real class bytecode calling the constructor is replaced by the one returning the mock.
The thing is that if you are using reflection, PowerMock can't know by reading the bytecode that this constructor will be called. It will only be known dynamically afterwards. So no mocking done.
If you really do need to create the class to be mocked by reflection, I would actually refactor the code a bit.
In Employee I would add something like
protected AppraisalCalculator getCalculator() {
try {
return AppraisalCalculator.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
while is a method dedicated to isolate the calculator construction.
The, just create a child class
#Test
public void testWithChildClass() {
// Note that you don't need PowerMock anymore
AppraisalCalculator acMock = Mockito.mock(AppraisalCalculator.class);
when(acMock.appraisal()).thenReturn(600);
Employee emp = new Employee() {
#Override
protected AppraisalCalculator getCalculator() {
return acMock;
}
};
int actualValue = emp.updateSalary();
int expectedValue = 600;
assertEquals(expectedValue, actualValue);
}
or a partial mock (spy)
#Test
public void test2() {
// No PowerMock either here
AppraisalCalculator acMock = Mockito.mock(AppraisalCalculator.class);
when(acMock.appraisal()).thenReturn(600);
Employee emp = spy(new Employee());
doReturn(acMock).when(emp).getCalculator();
int actualValue = emp.updateSalary();
int expectedValue = 600;
assertEquals(expectedValue, actualValue);
}

Invalid signature for SetUp or TearDown method - What am I doing wrong?

I am trying to do some dependency injection for my tests using nUnit. I'm new to TDD and nUnit so it's possible I am missing something simple. So basically I've created a SetUp method for my interfaces. I originally was using a constructor but I read it's bad to do this when doing TDD so I now using a method.
When I run my test I construct an object and assign it to the interface and then I call a method using that interface. I want to test if it can parse a string decimal.
When I run my test it says test failed and the message is:Invalid signature for SetUp or TearDown method
See below for the actual code:
public class DonorTests
{
private IDonor _Donor;
private IValidateInput _ValidInput;
//DonorTests(IDonor donor, IValidateInput validInput)
//{
// _Donor = donor;
// _ValidInput = validInput;
//}
[SetUp]
void Setup(IDonor donor, IValidateInput validInput)
{
_Donor = donor;
_ValidInput = validInput;
}
[Test]
public void HandleStringNotDecimal()
{
_ValidInput = new ValidateInput();
Assert.IsTrue(_ValidInput.IsDecimal("3445.3450"));
}
}
My class that uses this interface
public class ValidateInput : IValidateInput
{
public decimal RoundTwoDecimalPlaces(decimal amount)
{
return Math.Round(amount);
}
public bool IsDecimal(string amount)
{
decimal ParsedDecimal;
return Decimal.TryParse(amount, out ParsedDecimal);
}
public decimal ConvertToString(string value)
{
decimal ParsedDecimal;
Decimal.TryParse(value, out ParsedDecimal);
return ParsedDecimal;
}
}
You're injecting dependencies using constructor injection previously, right? I think you will not be able to perform dependency injection using method decorated with SetUpAttribute because such method has to be parameterless. Also Setup method has to be public, see this SO thread.
How are we typically dealing with similar situations in our company is:
[TestFixture]
public class DonorTests
{
private IDonor _Donor;
private IValidateInput _ValidInput;
[SetUp]
public void Setup()
{
_Donor = new Donor();
_ValidInput = new ValidateInput();
}
[Test]
public void HandleStringNotDecimal()
{
Assert.IsTrue(_ValidInput.IsDecimal("3445.3450"));
}
}
Or if construction of ValidInput and Donor is cheap then we simply create new instance for each test, having special method for that purpose so when we decide to test another implementation of IValidateInput then it is enough to change it in one place only:
[TestFixture]
public class DonorTests
{
[Test]
public void HandleStringNotDecimal()
{
var validInput = CreateValidateInput();
Assert.IsTrue(validInput .IsDecimal("3445.3450"));
}
private static IValidateInput CreateValidateInput()
{
return new ValidateInput();
}
}
Besides the cause mentioned in the accepted answer, I have met the same error when leaving method as non-public (private or protected).
NUnit most probably relies on reflection and does not deal with non-public methods, so special methods (i.e. decorated with NUnit specific attributes) must be public.

How to set members of mocked object

I remember reading an example which shows how to set member of a mocked object, for ex:
MyClass mockedClass = mock(MyClass.class);
//and something like this to set `someVariable` with some value
Mokito.set(mockedClass.someVariable, actual_value_intended_to_be_set);
Unfortunately I am not able to find that link again. Can someone give a reverence to
such examples or explain it here ?
If you want your mock's outward behavior to look like mockedClass.someVariable has actual_value_intended_to_be_set, you can write:
when(mockedClass.getSomeVariable()).thenReturn(actual_value_intended_to_be_set);
Happy mocking!
Is 'this' perhaps what you are looking for?
public class MyClassTest {
#InjectMocks private MyClass mockedClass;
#BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
mockedClass = new MyClass();
MockitoAnnotations.initMocks(this);
Mockito.when(getSomeVariable()).thenReturn(actual_value_intended_to_be_set);
}
#Test(groups = { "unit" })
public void testMyClass() throws Exception {
//almost too trivial an example since you just setup this.
Assert.assertEquals(getSomeVariable(), actual_value_intended_to_be_set);
}
}
It creates your MyClass object and sets the return value as well.

Moq: Verifying protected method on abstract class is called

This is my test
[TestClass]
public class RepositoryTests
{
private APurchaseOrderRepository _repository;
[TestInitialize]
public void TestInitialize()
{
_repository = new FakePurchaseOrderRepository();
}
[TestMethod]
public void RepositoryGetPurchaseOrdersForStoreCallsValidatePurchaseOrders()
{
var store = new Store();
var mockRepo = new Mock<APurchaseOrderRepository>();
mockRepo.Protected().Setup("ValidatePurchaseOrders", ItExpr.IsAny<List<PurchaseOrder>>());
_repository.GetPurchaseOrders(store);
mockRepo.Protected().Verify("ValidatePurchaseOrders", Times.Once(), ItExpr.IsAny<List<PurchaseOrder>>());
}
}
APurchaseOrderRepository and it's interface look like this
public interface IPurchaseOrderRepository
{
List<PurchaseOrder> GetPurchaseOrders(Store store);
}
public abstract class APurchaseOrderRepository : IPurchaseOrderRepository
{
public abstract List<PurchaseOrder> GetPurchaseOrders(Store store);
protected virtual bool ValidatePurchaseOrders(List<PurchaseOrder> purchaseOrders)
{
return true;
}
}
And my Fake
public class FakePurchaseOrderRepository : APurchaseOrderRepository
{
public override List<PurchaseOrder> GetPurchaseOrders(Store store)
{
var purchaseOrders = new List<PurchaseOrder>();
ValidatePurchaseOrders(purchaseOrders);
return purchaseOrders;
}
}
However, my test fails with:
Test method
PreSwapTests.RepositoryTests.RepositoryGetPurchaseOrdersForStoreCallsValidatePurchaseOrders
threw exception: Moq.MockException: Expected invocation on the mock
once, but was 0 times: mock =>
mock.ValidatePurchaseOrders(It.IsAny())
Configured setups: mock =>
mock.ValidatePurchaseOrders(It.IsAny()), Times.Never No
invocations performed.
What am I doing wrong?
Notes:
Moq.4.0.10827
Update:
I think it is this line mockRepo.Protected().Setup("ValidatePurchaseOrders");, because I need to add the parameters to it as a second argument, but I can't seem to get it correct.
Update 2:
Made some modifications, now it compiles, but isn't counting correctly...or something, error message and code are both updated above.
Realized I was doing this all wrong, changed my objects to work with this test
[TestMethod]
public void RepositoryGetPurchaseOrdersForStoreCallsValidatePurchaseOrders()
{
var store = new Store();
var mockPurchaseOrderProvider = new Mock<IPurchaseOrderProvider>();
var mockPurchaseOrderValidator = new Mock<IPurchaseOrderValidator>();
var purchaseOrderRepository = new PurchaseOrderRepository(mockPurchaseOrderProvider.Object, mockPurchaseOrderValidator.Object);
mockPurchaseOrderValidator.Setup(x => x.ValidatePurchaseOrders(It.IsAny<List<PurchaseOrder>>()));
purchaseOrderRepository.GetPurchaseOrders(store);
mockPurchaseOrderValidator.Verify(x => x.ValidatePurchaseOrders(It.IsAny<List<PurchaseOrder>>()), Times.Once());
}
This is a much better structure now I think.
It's because ValidatePurchaseOrders is not in your IPurchaseOrderRepository interface.
The repository is declared as private IPurchaseOrderRepository _repository; so it can only see what is in the interface.

Resources