Is it better to test with mock or without? - testing

A method can be tested either with mock object or without. I prefer the solution without mock when they are not necessary because:
They make tests more difficult to understand.
After refactoring it is a pain to fix junit tests if they have been implemented with mocks.
But I would like to ask your opinion. Here the method under test:
public class OndemandBuilder {
....
private LinksBuilder linksBuilder;
....
public OndemandBuilder buildLink(String pid) {
broadcastOfBuilder = new LinksBuilder(pipsBeanFactory);
broadcastOfBuilder.type(XXX).pid(pid);
return this;
}
Test with mocks:
#Test
public void testbuildLink() throws Exception {
String type = "XXX";
String pid = "test_pid";
LinksBuilder linkBuilder = mock(LinksBuilder.class);
given(linkBuilder.type(type)).willReturn(linkBuilder);
//builderFactory replace the new call in order to mock it
given(builderFactory.createLinksBuilder(pipsBeanFactory)).willReturn(linkBuilder);
OndemandBuilder returnedBuilder = builder.buildLink(pid);
assertEquals(builder, returnedBuilder); //they point to the same obj
verify(linkBuilder, times(1)).type(type);
verify(linkBuilder, times(1)).pid(pid);
verifyNoMoreInteractions(linkBuilder);
}
The returnedBuilder obj within the method buildLink is 'this' that means that builder and returnedBuilder can't be different because they point to the same object in memory so the assertEquals is not really testing that it contains the expected field set by the method buildLink (which is the pid).
I have changed that test as below, without using mocks. The below test asserts what we want to test which is that the builder contains a LinkBuilder not null and the LinkBuilder pid is the one expected.
#Test
public void testbuildLink() throws Exception {
String pid = "test_pid";
OndemandBuilder returnedBuilder = builder.buildLink(pid);
assertNotNull(returnedBuilder.getLinkBuilder());
assertEquals(pid, returnedBuilder.getLinkBuilder().getPid());
}
I wouldn't use mock unless they are necessary, but I wonder if this makes sense or I misunderstand the mock way of testing.

Mocking is a very powerful tool when writing unit tests, in a nut shell where you have dependencies between classes, and you want to test one class that depends on another, you can use mock objects to limit the scope of your tests so that you are only testing the code in the class that you want to test, and not those classes it depends on. There is no point me explaining further, I would highly recommend you read the brilliant Martin Fowler work Mocks Aren't Stubs for a full introduction into the topic.
In your example, the test without mocks is definitely cleaner, but you will notice that your test exercises code in both the OndemandBuilder and LinksBuilder classes. It may be that this is what you want to do, but the 'problem' here is that should the test fail, it could be due to issues in either of those two classes. In your case, because the code in OndemandBuilder.buildLink is minimal, I would say your approach is OK. However, if the logic in this function was more complex, then I would suggest that you would want to unit test this method in a way that didn't depend on the behavior of the LinksBuilder.type method. This is where mock objects can help you.
Lets say we do want to test OndemandBuilder.buildLink independent of the LinksBuilder implementation. To do this, we want to be able to replace the linksBuilder object in OndemandBuilder with a mock object - by doing this we can precisely control what is returned by calls to this mock object, breaking the dependency on the implementation of LinksBuilder. This is where the technique Dependency Injection can help you - the example below shows how we could modify OndemandBuilder to allow linksBuilder to be replaced with a mock object (by injecting the dependency in the constructor):
public class OndemandBuilder {
....
private LinksBuilder linksBuilder;
....
public class OndemandBuilder(LinksBuilder linksBuilder) {
this.linksBuilder = linksBuilder;
}
public OndemandBuilder buildLink(String pid) {
broadcastOfBuilder = new LinksBuilder(pipsBeanFactory);
broadcastOfBuilder.type(XXX).pid(pid);
return this;
}
}
Now, in your test, when you create your OndemandBuilder object, you can create a mock version of LinksBuilder, pass it into the constructor, and control how this behaves for the purpose of your test. By using mock objects and dependency injection, you can now properly unit test OndemandBuilder independent of the LinksBuilder implementation.
Hope this helps.

It all dependent upon what you understand by UNIT testing.
Because when you are trying to unit test a class , it means you are not worried about the underlying system/interface. You are assuming they are working correctly hence you just mock them. And when i say you are ASSUMING means you are unit testing the underlying interface separately.
So when you are writing your JUnits without mocks essentially you are doing a system or an integration test.
But to answer your question both ways have their advantages/disadvantages and ideally a system should have both.

Related

How to get 100% test coverage over a DTO object class's getters when asserting function returns expected DTO object?

I'm unit testing an ASP.Net Core API by asserting that my repo layer returns a DTO object. As I'm testing behavior, I don't exactly care what values my DTO object has, so I'm autogenerating them using AutoFixture. I'm also trying to satisfy my company's code smell check, which requires our PRs to have a near 100% test coverage. When I mock my ORM to return my DTO object when called and in turn the function under test returns that object, I end up with my actual being the same object as my expected. When asserting with fluent assertion, it sees the object reference are equal and passes my test. However for test coverage, I will not see a coverage over the DTO's properties' getters. If the object reference where different, fluent assertion calls the getters. How do I force fluent assertion to always check the value of all properties by calling all the getters?
I've tried using ComparingByValue<T> and ComparingByMember<T>. I've also tried IncludingProperties(), IncludingMembers(), IncludingAllDeclaredProperties(), and IncludingAllRuntimeProperties().
[Fact]
public void GivenObjectReferenceIsTheSame_FluentAssertionDoesntCallTheGetters()
{
var someDTO = _fixture.Create<SomeDTO>();
var otherDTO = someDTO;
otherDTO.Should().BeEquivalentTo(someDTO);
}
[Fact]
public void GivenObjectReferenceIsDifferent_FluentAssertionCallsTheGetters()
{
var someDTO = _fixture.Create<SomeDTO>();
var otherDTO = JsonConvert.DeserializeObject<SomeDTO>(JsonConvert.SerializeObject(someDTO));
otherDTO.Should().BeEquivalentTo(someDTO);
}
I would like a way to always force fluent assertion to call the getters in order to get test coverage over the DTOs without having to explicitly write useless tests over the DTOs
The short answer is that you can't. You've asked FA to assert that the objects are equivalent, and in fact, they are the same. This satisfies what FA tries to do. The only alternative is to to pass in another instance which has its properties set to the values of the expectation. This can even be an anonymous object. ComparingByValue is only useful to force FA to ignore the Equals implementation and compare the individual fields and properties.

Why are mocking test frameworks helpful?

It seems like all of the Mockito examples I have looked at, "fake" the behavior of the object they are testing.
If I have an object that has a the method:
public int add(int a, int b) {return a+b}
I would simply use JUnit to assert whether two integers passed in would result in the correct output.
With all of the examples I've seen with Mockito, people are doing things like when.Object.add(2,3).thenReturn(5). What's the point of using this testing framework, if all you're doing is telling the object how to act on the test side, rather than the object side?
Mocking frameworks are good for testing a system by mocking that system's dependencies; you wouldn't use a mocking framework to mock or stub add if you are testing add. Let's break this out a bit further:
Testing add
A mocking framework is not good for testing your add method above. There are no dependencies other than the very stable and extremely-well-tested JVM and JRE.
public int add(int a, int b) {return a+b}
However, it might be good for testing your add method if it were to interact with another object like this:
public int add(int a, int b, AdditionLogger additionLogger) {
int total = a + b;
additionLogger.log(a, b, total);
return total;
}
If AdditionLogger isn't written yet, or if it's written to communicate with a real server or other external process, then a mocking framework would absolutely be useful: it would help you come up with a fake implementation of AdditionLogger so you could test your real method's interactions with it.
#Test public void yourTest() {
assertEquals(5, yourObject.add(2, 3, mockAdditionLogger));
verify(mockAdditionLogger).log(2, 3, 5);
}
Testing add's consumers
Coincidentally, a mocking framework is also unlikely to be good for testing consumers of your method above. After all, there is nothing particularly dangerous about a call to add, so assuming it exists you can probably call the real one in an external test. 2 + 3 will always equal 5, and there are no side effects from your calculation, so there's very little to be gained by mocking or verifying.
However, let's give your object another method that adds two numbers with a little bit of random noise:
public int addWithNoise(int a, int b) {
int offset = new Random().nextInt(11) - 5; // range: [-5, 5]
int total = a + b + offset;
return total;
}
With this, it may be very hard for you to write a robust assert-style test against this method; after all, the result is going to be somewhat random! Instead, to make an assert-style test easier, maybe we can stub out addWithNoise to make some of this more predictable.
#Test public void yourTest() {
when(yourObjectMock.addWithNoise(2, 3)).thenReturn(6);
// You're not asserting/verifying the action you stub, you're making the dependency
// *fast and reliable* so you can check the logic of *the real method you're testing*.
assertEquals(600, systemUnderTestThatConsumesYourObject.doThing(yourObjectMock));
}
In summary
It can be easier to explain mocking and mock syntax when interacting with well-known operations like add or well-known interfaces like List, but those examples are not usually realistic cases where mocks are needed. Remember that mocking is only really useful for simulating the dependencies around your system-under-test when you can't use real ones.
Goal of unit-testing is to test the functionality without connecting to any external systems. If you are connecting to any external system, that is considered integration testing.
While performing unit-testing, a system may need some data that could have been retrieved from external systems as database, web/rest services, API etc during Systems/Integration testing. In such scenarios, we need to supply mock/fake data to test some business rules, or any other form of logic.
With above, unit-tests ensure that a particular unit of code works with given set of fake/mocked data, and should behave in similar manner in integrated environment.

NSubstitute Test against classes (VB.net)

First of all I'm a beginner in unit tests. For my tests i want to use NSubstitute, so I read the tutorial on the website and also the mock comparison from Richard Banks. Both of them are testing against interfaces, not against classes. The statement is "Generally this [substituted] type will be an interface, but you can also substitute classes in cases of emergency."
Now I'm wondering about the purpose of testing against interfaces. Here is the example interface from the NSubstitute website (please note, that i have converted the C#-code in VB.net):
Public Interface ICalculator
Function Add(a As Double, b As Double) As Double
Property Mode As String
Event PoweringUp As EventHandler
End Interface
And here is the unit test from the website (under the NUnit-Framework):
<Test>
Sub ReturnValue_For_Methods()
Dim calculator = Substitute.For(Of ICalculator)()
calculator.Add(1, 2).Returns(3)
Assert.AreEqual(calculator.Add(1, 2), 3)
End Sub
Ok, that works and the unit test will perform successful. But what sense makes this? This do not test any code. The Add-Method could have any errors, which will not be detected when testing against interfaces - like this:
Public Class Calculator
Implements ICalculator
Public Function Add(a As Double, b As Double) As Double Implements ICalculator.Add
Return 1 / 0
End Function
...
End Class
The Add-Method performs a division by zero, so the unit test should fail - but because of testing against the interface ICalculator the test is successful.
Could you please help me to understand that? What sense makes it, not to test the code but the interface?
Thanks in advance
Michael
The idea behind mocking is to isolate a class we are testing from its dependencies. So we don't mock the class we are testing, in this case Calculator, we mock an ICalculator when testing a class that uses an ICalculator.
A small example is when we want to test how something interacts with a database, but we don't want to use a real database for some quick tests. (Please excuse the C#.)
[Test]
public void SaveTodoItemToDatabase() {
var substituteDb = Substitute.For<IDatabase>();
var todoScreen = new TodoViewModel(substituteDb);
todoScreen.Item = "Read StackOverflow";
todoScreen.CurrentUser = "Anna";
todoScreen.Save();
substituteDb.Received().SaveTodo("Read StackOverflow", "Anna");
}
The idea here is we've separated the TodoViewModel from the details of saving to the database. We don't want to worry about configuring a database, or getting a connection string, or having data from previous test runs interfering with future tests runs. Testing with a real database can be very valuable, but in some cases we just want to test a smaller unit of functionality. Mocking is one way of doing this.
For the real app, we'll create a TodoViewModel with a real implementation of IDatabase, and provided that implementation follows the expected contract of the interface then we can have a reasonable expectation that it will work.
Hope this helps.
Update in response to comment
The test for TodoViewModel assumes the implementation of the IDatabase works so we can focus on that class' logic. This means we'll probably want a separate set of tests for implementations of IDatabase. Say we have a SqlServerDbimplementation, then we can have some tests (probably against a real database) that check it does what it promises. In those tests we'll no longer be mocking the database interface, because that's what we're testing.
Another thing we can do is have "contract tests" which we can apply to any IDatabase implementation. For example, we could have a test that says for any implementation, saving an item then loading it up again should return the same item. We can then run those tests against all implementations, SqlDb, InMemoryDb, FileDb etc. In this way we can state our assumptions about the dependencies we're mocking, then check that the actual implementations meet our assumptions.

Dependency injection of local variable returned from method

I'm (somewhat) new to DI and am trying to understand how/why it's used in the codebase I am maintaining. I have found a series of classes that map data from stored procedure calls to domain objects. For example:
Public Sub New(domainFactory As IDomainFactory)
_domainFactory = domainFactory
End Sub
Protected Overrides Function MapFromRow(row As DataRow) As ISomeDomainObject
Dim domainObject = _domainFactory.CreateSomeDomainObject()
' Populate the object
domainObject.ID = CType(row("id"), Integer)
domainObject.StartDate = CType(row("date"), Date)
domainObject.Active = CType(row("enabled"), Boolean)
Return domainObject
End Function
The IDomainFactory is injected with Spring.Net. It's implementation simply has a series of methods that return new instances of the various domain objects. eg:
Public Function CreateSomeDomainObject() As ISomeDomainObject
Return New SomeDomainObject()
End Function
All of the above code strikes me as worse than useless. It's hard to follow and does nothing of value. Additionally, as far as I can tell it's a misuse of DI as it's not really intended for local variables. Furthermore, we don't need more than one implementation of the domain objects, we don't do any unit testing and if we did we still wouldn't mock the domain objects. As you can see from the above code, any changes to the domain object would be the result of changes to the SP, which would mean the MapFromRow method would have to be edited anyway.
That said, should I rip this nonsense out or is it doing something amazingly awesome and I'm missing it?
The idea behind dependency injection is to make a class (or another piece of code) independent on a specific implementation of an interface. The class outlined above does not know which class implements IDomainFactory. A concrete implementation is injected through its constructor and later used by the method MapFromRow. The domain factory returns an implementation of ISomeDomainObject which is also unknown.
This allows you supplement another implementation of these interfaces without having to change the class shown above. This is very practical for unit tests. Let's assume that you have an interface IDatabase that defines a method GetCustomerByID. It is difficult to test code that uses this method, since it depends on specific customer records in the database. Now you can inject a dummy database class that returns customers generated by code that does not access a physical database. Such a dummy class is often called a mock object.
See Dependency injection on Wikipedia.

Rhino Mocks - Stub .Expect vs .AssertWasCalled

OK, I know there has been a lot of confusion over the new AAA syntax in Rhino Mocks, but I have to be honest, from what I have seen so far, I like. It reads better, and saves on some keystrokes.
Basically, I am testing a ListController which is going to basically be in charge of some lists of things :) I have created an interface which will eventually become the DAL, and this is of course being stubbed for now.
I had the following code:
(manager is the system under test, data is the stubbed data interface)
[Fact]
public void list_count_queries_data()
{
data.Expect(x => x.ListCount(1));
manager.ListCount();
data.VerifyAllExpectations();
}
The main aim of this test is to just ensure that the manager is actually querying the DAL. Note that the DAL is not actually even there, so there is no "real" value coming back..
However, this is failing since I need to change the expectation to have a return value, like:
data.Expect(x => x.ListCount(1)).Return(1);
This will then run fine, and the test will pass, however - what is confusing me is that at this point in time, the return value means nothing. I can change it to 100, 50, 42, whatever and the test will always pass?
This makes me nervous, because a test should be explicit and should totally fail if the expected conditions are not met right?
If I change the test to (the "1" is the expected ID the count is linked to):
[Fact]
public void list_count_queries_data()
{
manager.ListCount();
data.AssertWasCalled(x => x.ListCount(1));
}
It all passes fine, and if I switch the test on it's head to AssertWasNotCalled, it fails as expected.. I also think it reads a lot better, is clearer about what is being tested and most importantly PASSES and FAILS as expected!
So, am I missing something in the first code example? What are your thoughts on making assertions on stubs? (there was some interesting discussion here, I personally liked this response.
What is your test trying to achieve?
What behaviour or state are you verifying? Specifically, are you verifying that the collaborator (data) is having its ListCount method called (interaction based testing), or do you just want to make ListCount return a canned value to drive the class under test while verifying the result elsewhere (traditional state based testing)?
If you want set an expectation, use a mock and an expectation:
Use MockRepository.CreateMock<IMyInterface>() and myMock.Expect(x => x.ListCount())
If you want to stub a method, use MockRepository.CreateStub<IMyInterface>() and myStub.Stub(x => x.ListCount()).
(aside: I know you can use stub.AssertWasCalled() to achieve much the same thing as mock.Expect and with arguably better reading syntax, but I'm just drilling into the difference between mocks & stubs).
Roy Osherove has a very nice explanation of mocks and stubs.
Please post more code!
We need a complete picture of how you're creating the stub (or mock) and how the result is used with respect to the class under test. Does ListCount have an input parameter? If so, what does it represent? Do you care if it was called with a certain value? Do you care if ListCount returns a certain value?
As Simon Laroche pointed out, if the Manager is not actually doing anything with the mocked/stubbed return value of ListCount, then the test won't pass or fail because of it. All the test would expect is that the mocked/stubbed method is called -- nothing more.
To better understand the problem, consider three pieces of information and you will soon figure this out:
What is being tested
In what situation?
What is the expected result?
Compare:
Interaction based testing with mocks. The call on the mock is the test.
[Test]
public void calling_ListCount_calls_ListCount_on_DAL()
{
// Arrange
var dalMock = MockRepository.Mock<IDAL>();
var dalMock.Expect(x => x.ListCount()).Returns(1);
var manager = new Manager(dalMock);
// Act
manager.ListCount();
// Assert -- Test is 100% interaction based
dalMock.VerifyAllExpectations();
}
State based testing with a stub. The stub drives the test, but is not a part of the expectation.
[Test]
public void calling_ListCount_returns_same_count_as_DAL()
{
// Arrange
var dalStub = MockRepository.Stub<IDAL>();
var dalStub.Stub(x => x.ListCount()).Returns(1);
var manager = new Manager(dalMock);
// Act
int listCount = manager.ListCount();
// Assert -- Test is 100% state based
Assert.That(listCount, Is.EqualTo(1),
"count should've been identical to the one returned by the dal!");
}
I personally favour state-based testing where at all possible, though interaction based testing is often required for APIs that are designed with Tell, Don't Ask in mind, as you won't have any exposed state to verify against!
API Confusion. Mocks ain't stubs. Or are they?
The distinction between a mock and a stub in rhino mocks is muddled. Traditionally, stubs aren't meant to have expectations -- so if your test double didn't have its method called, this wouldn't directly cause the test to fail.
... However, the Rhino Mocks API is powerful, but confusing as it lets you set expectations on stubs which, to me, goes against the accepted terminology. I don't think much of the terminology, either, mind. It'd be better if the distinction was eliminated and the methods called on the test double set the role, in my opinion.
I think it has to do with what your manager.ListCount() is doing with the return value.
If it is not using it then your DAL can return anything it won't matter.
public class Manager
{
public Manager(DAL data)
{
this.data = data
}
public void ListCount()
{
data.ListCount(1); //Not doing anything with return value
DoingSomeOtherStuff();
}
}
If your list count is doing something with the value you should then put assertions on what it is doing. For exemple
Assert.IsTrue(manager.SomeState == "someValue");
Have you tried using
data.AssertWasCalled(x => x.ListCount(1) = Arg.Is(EXPECTED_VALUE));