easymock missing behavior definition - easymock

i m writing test using easymock, and i created the following mock object for my test,
auditor = createMock(Auditor.class);
auditor.start(isA(Audit.class)); //record
replay(auditor);
expect(auditor.getAudit("my-process")).andReturn(null);
replay(auditor);
Auditor class has a method 'start(Audit.class)', i recorded it first, then stub its other method 'getAudit()', then replay them all. however it complained:missing behavior definition from previous call start(isA(Audit.class)), what did i do wrong here? thanks,

You have specified the mock behavior for "auditor.start(...)" method incorrectly. Assuming it returns void, one way to do it would be:
#Test
public void testAuditor() {
Auditor auditor = EasyMock.createMock(Auditor.class);
auditor.start(Audit.class);
EasyMock.expectLastCall(); //record
EasyMock.expect(auditor.getAudit("my-process")).andReturn(null);
EasyMock.replay(auditor);
//rest of your test code
}

Related

EasyMock - CreateNiceMock

A fairly straightforward question regarding EasyMock. Read up a bunch of resources but not sure what I am missing:
The following snippet is creating a unit test using Test-ng:
#Test(groups = "unit")
public class SchoolTestEasyMock {
#Test
public void test1() {
School mockSchool = EasyMock.createNiceMock(School.class);
EasyMock.replay(mockSchool);
System.out.println(mockSchool.getSchoolNumber());
}
}
Let's assume the School class has a simple getter 'getSchoolNumber' that returns an Integer.
The snippet above is printing a 'null' to the console. Since I'm creating a 'nice' mock shouldn't the 'getSchoolNumber' return a default value of 0? Am I missing something while creating the nice mock?
From the documentation:
If you would like a "nice" Mock Object that by default allows all method calls and returns appropriate empty values (0, null or false), use niceMock() instead.
As Integer is an object, the default value is null.
If you change the return type of the method to int, the value will be 0 as expected.

Is it bad to wrap singleton instance methods in static methods?

Is there a con to implementing a singleton that wraps instance methods with static ones?
For example:
public void DoStuff() { instance._DoStuff(); }
private void _DoStuff() {
...
}
And of course instance would be static. But it would be nicer to call:
Singleton.DoStuff();
Instead of:
Singleton.GetInstance().DoStuff();
I think it depends.
First the GetInstance() really should be used for getting an object back and then using that else where in your code. The Singleton should just help guarantee a single instance of that object exists.
Next if you want to make DoStuff static go ahead, though you have to know to call it that way everywhere else in your code.
So you really have this difference:
var instance = Singleton.GetInstance();
...
instance.DoStuff ()
Vs
Singleton.DoStuff ()
This means that you can pass a singleton object around and not have to know static calls.
Also, I have to mention that Singletons if not used properly can lead to a nightmare in unit testing: http://misko.hevery.com/2008/08/25/root-cause-of-singletons/

How to JUnit test an add method for a custom made ArrayList?

I implemented my custom ArrayList using a resizeable Array, and I would like to unit test my add method to check if the right value getting inserted to the right position. My add method looks like this:
public class MyArrayList<T> implements ArrayListInterface {
private int max=20;
private int index = 0;
private int[] a = new int[max];
#Override
public void add(int value) {
if(index>max-1) {
resize();
}
a[index] = value;
index++;
}
I am aware, I could just make my method boolean and check what the method returns, but I would like to check that the right value added to the right position. My problem is that my Array is private, and that way it is only possible to reach its value through a getter. Is it a good solution to make a getter for my Array, and compare that to the actual result of the test, or what would be the best solution to test this method?
I have checked couple of other stackoverflow questions in the same topic, but I couldn't find any solution for my problem.
Add a get() (get(position), getLast(), etc.) method to your class and test using this method. Unit tests should exercise the class through its interfaces, without caring about the internal implementation. Any other class that will interact with your MyArrayList will do so through add() and get().

How to populate method's return values with AutoFixture

I would like to auto-generate a method's return values in a non-deterministic manner, i.e. with every call/test run to I expect a method to return random value. For the moment it returns always default values of the method calls:
public interface IReturn
{
bool BoolMethod();
int IntMethod();
}
[Fact]
public void AllReturnsFromAutofixtureMethodsAreFalse()
{
IFixture fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
IEnumerable<IReturn> theBools = fixture.CreateMany<IReturn>();
Assert.True(theBools.All(tb => tb.BoolMethod() == false));
Assert.True(theBools.All(tb => tb.IntMethod() == 0));
}
In questions like this one can find a way how to achieve similar thing for properties, however not methods. Any idea?
I haven't used AutoFixture with NSubstitute customization, however by analogy to Moq library, It seems that AutoConfiguredNSubstituteCustomization class should be used to achieve advanced AutoFixture faking behavior such that you want to. Using it you can auto-generate results from stubbed methods, as well as it is possible to create mock objects chains, injecting freezed objects into chain, an so on.

unit test to verify that a repository loads an entity from the database correctly

I have a simple standard repository that loads a composite entity from the database. It injects all dependencies it need to read the complete entity tree from a database through IDbConnection (wich gives the repository access to IDbCommand, IDbTransaction, IDataReader) that I could mock.
public class SomeCompositionRootEntityRepository :
IRepository<SomeCompositionRoot>
{
public RecipeRepository(IDbConnection connection) { ... }
public void Add(SomeCompositionRootEntity item) { ... }
public bool Remove(SomeCompositionRootEntity item) { ... }
public void Update(SomeCompositionRootEntity item) { ... }
public SomeCompositionRootEntity GetById(object id) { ... }
public bool Contains(object id) { ... }
}
The question is how would I write unit test for this in a good way? If I want to test that the reposity has read the whole tree of objects and it has read it correcty, I would need to write a hughe mock that records and verifies the read of each and every property of each and every object in the tree. Is this really the way to go?
Update:
I think I need to refactor my repository to break the repository functionality and unit test into smaller units. How could this be done?
I am sure I do not want to write unit test that involve reading and writing from and to an actual database.
The question is: What functionality do you want to test?
Do you want to test that your repository actually loads something? In this case I would write a few (!) tests that go through the database.
Or do you want to test the functionality inside the repository methods? In this case your mock approach would be appropriate.
Or do you want to make sure that the (trivial) methods of your repository aren't broken? In this case mocks and one test per method might be sufficient.
Just ask yourself what the tests shall ensure and design them along this target!
I think I understand your question so correct me if I'm wrong...
This is a where you cross the line from unit to integration. The test makes sense (I've written these myself), but you're not really testing your repository, rather you're testing that your entity (SomeCompositionRoot) maps correctly. It isn't inserting/updating, but does involve a read to the database.
Depending on what ORM you use, you can do this a million different ways and typically its fairly easy.
::EDIT::
like this for linq for example ...
[TestMethod]
public void ShouldMapBlahBlahCorrectly()
{
CheckBasicMapping<BlahBlah>();
}
private T CheckBasicMapping<T>() where T : class
{
var target = _testContext.GetTable<T>().FirstOrDefault();
target.ShouldNotBeNull();
return target;
}

Resources