Mock objects, nUnit, call log and log4net - unit-testing

A very often scenario of unit test is as follows:
public void SetUp()
{
this.callLog = new StringBuilder();
}
public void TestBuzzBar()
{
var bar = new Bar(new MockFoo(callLog));
bar.Buzz(17);
Assert.AreEqual("MockFoo.Init(17) MockFoo.PrepareStuff MockFoo.DoTheJob ", callLog.ToString());
}
... with MockFoo implementing an IFoo interface by just appending strings a call log. It requires a lot of code handling with callLog in mocks.
Is it a good idea to use log4net to collect call log?

To answer your question: log4net is a great logging framework. It is easy to set up and use. I have used it in unit tests with a MemoryAppender which essentially enables you to go back and peek at what have been logged during the test. This technique works for both mocks and SUT.

Related

How to decide what to mock in Java Unit Tests?

I am trying to write a Unit Tests to a legacy code using Mockito.
But I am not able to understand how do I mock it. Can some please help.
The real problem I am facing is actually I am not able to decide how to make a decision on what exactly is to be mocked? Below is the code. I have looked at numerous videos on YouTube and read many Mockito Tutorials but all of them seem to be guiding mostly about how to use the Mockito Framework.
The basic idea of what to Mock is still unclear. Please guide if you have a better source. I do understand that the code showed below does not really showcase the best coding practice.
public class DataFacade {
public boolean checkUserPresent(String userId){
return getSomeDao.checkUserPresent(userId);
}
private SomeDao getSomeDao() {
DataSource dataSource = MyDataSourceFactory.getMySQLDataSource();
SomeDao someDao = new SomeDao(dataSource);
}
}
Well, a Unittest, as the name implies, tests a unit. You should mock anything that isn't part of that unit, especially external dependencies. For example, a DAO is normally a good example for something that will be mocked in tests where the class under tests uses it, because otherwise you would really have actual data access in your test, making it slower and more prone to failure because of external reasons (for example, if your dao connects to a Datasource, that Datasource's target (for example, the database) may be down, failing your test even if the unit you wanted to test is actually perfectly fine). Mocking the DAO allows you to test things independently.
Of course, your code is bad. Why? You are creating everything in your method by calling some static factory method. I suggest instead using dependency injection to inject the DAO into your facade, for example...
public DataFacade(SomeDao someDao) {
this.someDao = someDao;
}
This way, when instantiating your DataFacade, you can give it a dao, which means, in your test you can give it a mock, for example...
#Test
public void testSomething() {
SomeDao someDaoMock = Mockito.mock(SomeDao.class);
DataFacade toTest = new DataFacade(someDaoMock);
...now you can prepare your mock to do something and then call the DataFace method
}
Dependency injection frameworks like Spring, Google Guice, etc. can make this even easier to manage, but the first step is to stop your classes from creating their own dependencies, but let the dependencies be given to them from the outside, which makes the whole thing a lot better.
You should "mock" the inner objects that you use in your methods.
For example if you write unit tests for DataFacade->checkUserPresent, you should mock the getSomeDao field.
You have a lot of ways to do it, but basically you can make getSomeDao to be public field, or get it from the constructor. In your test class, override this field with mocked object.
After you invoke DataFacade->checkUserPresent method, assert that checkUserPresent() is called.
For exmaple if you have this class:
public class StudentsStore
{
private DbReader _db;
public StudentsStore(DbReader db)
{
_db = db;
}
public bool HasStudents()
{
var studentsCount = _db.GetStudentsCount();
if (studentsCount > 0)
return true;
else
return false;
}
}
And in your test method:
var mockedDb = mock(DbReader.class);
when(mockedDb.GetStudentsCount()).thenReturn(1);
var store = new StudentsSture(mockedDb);
assertEquals(true,store.HasStudents());

When using Ninject for dependeny injection is it best practices to use Ninject in your unit tests or use a mocking framework

I am using ninject to inject dependencies in my production environment. I see two options when it comes to writing unit tests. I can either create concrete classes and inject them using ninject, Or I can use a mocking framework like just mock.
My thought process is to just use both and have the deciding factor be whether or not the TestInterface can be constructed in a reusable way. This way we dont waste time writing the same Mocked method to return an empty list over and over again.
Is there a best practice for this type of thing?
With unit tests on class, it doesn't make a lot of sense to include the DI container in the "system under test" (SUT).
by principle, a class unit test should test the class and the class only
usually you can't "reuse" the bindings in the unit test, you have to create them unit-test specific. Therefore you're only re-testing ninject, but not how you're applying it. Ninject is already tested. So no real benefit for you.
If you do acceptance testing / unit testing on component or application level, then it makes perfectly sense to include Ninject in the SUT.
For a class-level unit test one usually takes a dynamic proxy based mocking framework like MOQ or FakeItEasy.
given an implementation:
public interface IDependency {
void Foo(string bar);
}
public class SomeClass
{
private readonly IDependency dependency;
public SomeClass(IDependency dependency)
{
this.dependency = dependency;
}
public void SomeMethod(string arg)
{
this.dependency.Foo(arg);
}
}
a test would look like (xUnit flavor):
public class SomeClassTest
{
private readonly Mock<IDependency> dependency;
private SomeClass testee;
public SomeClassTest()
{
this.dependency = new Mock<IDependency>();
this.testee = new SomeClass(this.dependency.Object);
}
[Fact]
public void SomeMethod_MustPassArgumentToFoo()
{
const string expectedArgument = "AnyArgument;
this.testee.SomeMethod(expectedArgument);
this.dependency.Verify(x => x.Foo(expectedArgument));
}
}
JustMock has NInject built into it plus a mocking container based on it.
Injecting mocks of dependencies is done automatically when you fetch the instance for the first time:
var container = new MockingContainer<ClassUnderTest>();
var testee = container.Instance;
Plus, you can use NInject's syntax for fine-grained control of the injection behavior, as well as JustMock's syntax for configuring mock behavior.

How can I unit test a method with database access?

I have already had some difficulties on unit tests and I am trying to learn it while using a small project I currently am working on and I ran into this problem these two problems that I hope you can help me with
1- My project is an MVC project. At which level should my unit tests start? They should focus only on the business layer? Should they also test actions on my controllers?
2- I have a method that verifies an username format and then access the DB to check if it is available for use. The return is a boolean whether this username is available or not.
Would one create a unit test for such a method?
I would be interested on testing the format verification, but how would I check them without querying the DB? Also, if the formats are correct, but the username is already in use, I will get a false value, but the validation worked. I could decouple this method, but the DB verification should only happen if the format is correct, so they should somehow be tied.
How would someone with unit tests knowledge solve this issue. Or how would someone refactor this method to be able to test it?
I could create a stub for the DB access, but how would I attach it to my project on the user testing but detach it when running locally?
Thanks!
In your specific case, one easy thing you could do is decompose your verification method into 3 different methods: one to check formatting, one to check DB availability, and one to tie them both together. This would allow you to test each of the sub-functions in isolation.
In more complex scenarios, other techniques may be useful. In essence, this is where dependency injection and inversion of control come in handy (unfortunately, those phrases mean different things to different people, but getting the basic ideas is usually a good start).
Your goal should be to decouple the concept of "Check if this username is available" from the implementation of checking the DB for it.
So, instead of this:
public class Validation
{
public bool CheckUsername(string username)
{
bool isFormatValid = IsFormatValid(username);
return isFormatValid && DB.CheckUsernameAvailability(username);
}
}
You could do something like this:
public class Validation
{
public bool CheckUsername(string username,
IUsernameAvailabilityChecker checker)
{
bool isFormatValid = IsFormatValid(username);
return isFormatValid && checker.CheckUsernameAvailability(username);
}
}
And then, from your unit test code, you can create a custom IUsernameAvailabilityChecker which does whatever you want for testing purposes. On the other hand, the actual production code can use a different implementation of IUsernameAvailabilityChecker to actually query the database.
Keep in mind that there are many, many techniques to solve this kind of testing problem, and the examples I gave are simple and contrived.
Testing against outside services can be done using mocking. If you've done a good job using interfaces it's very easy to mock various parts of your application. These mocks can be injected into your unit and used like it would normally handle it.
You should start unit testing as soon as possible. If your application is not complete or code needed for testing is absent you can still test against some interface you can mock.
On a sidenote: Unit testing is about testing behavior and is not an effective way to find bugs. You will find bugs with testing but it should not be your goal.
For instance:
interface UserService {
public void setUserRepository(UserRepository userRepository);
public boolean isUsernameAvailable(String username);
}
class MyUserService implements UserService {
private UserRepository userRepository;
public vois setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public boolean isUsernameAvailable(String username) {
return userRepository.checkUsernameAvailability(username);
}
}
interface UserRepository {
public boolean checkUsernameAvailability(String username);
}
// The mock used for testing
class MockUserRepository {
public boolean checkUsernameAvailability(String username) {
if ("john".equals(username)) {
return false;
}
return true;
}
}
class MyUnitTest {
public void testIfUserNotAvailable() {
UserService service = new UserService();
service.setUserRepository(new MockUserRepository);
assertFalse(service.isUsernameAvailable('john')); // yep, it's in use
}
public void testIfUserAvailable() {
UserService service = new UserService();
service.setUserRepository(new MockUserRepository);
assertTrue(service.isUsernameAvailable('mary')); // yep, is available
}
}

How to unit test netty handler

I implement a handler which extends SimpleChannelHandler, and overrides some methods such as channelConnected, messageReceived. However, I am wondering how to unit test it?
I searched about "netty unit test" and found one article which said considering CodecEmbedder, but I am still not sure how to begin. Do you have any example or advice on how to unit test Netty code?
Thanks a lot.
In Netty, there are different ways to test your networking stack.
Testing ChannelHandlers
You can use Netty's EmbeddedChannel to mock a netty connection for testing, an example of this would be:
#Test
public void nettyTest() {
EmbeddedChannel channel = new EmbeddedChannel(new StringDecoder(StandardCharsets.UTF_8));
channel.writeInbound(Unpooled.wrappedBuffer(new byte[]{(byte)0xE2,(byte)0x98,(byte)0xA2}));
String myObject = channel.readInbound();
// Perform checks on your object
assertEquals("☢", myObject);
}
This test above tests for StringDecoder ability to decode unicode correct (example from this bug posted by me)
You can also test the encoder direction using EmbeddedChannel, for this you should use writeOutBound and readInbound.
More Examples:
DelimiterBasedFrameDecoderTest.java:
#Test
public void testIncompleteLinesStrippedDelimiters() {
EmbeddedChannel ch = new EmbeddedChannel(new DelimiterBasedFrameDecoder(8192, true,
Delimiters.lineDelimiter()));
ch.writeInbound(Unpooled.copiedBuffer("Test", Charset.defaultCharset()));
assertNull(ch.readInbound());
ch.writeInbound(Unpooled.copiedBuffer("Line\r\ng\r\n", Charset.defaultCharset()));
assertEquals("TestLine", releaseLater((ByteBuf) ch.readInbound()).toString(Charset.defaultCharset()));
assertEquals("g", releaseLater((ByteBuf) ch.readInbound()).toString(Charset.defaultCharset()));
assertNull(ch.readInbound());
ch.finish();
}
More examples on github.
ByteBuf
To test if you use your bytebufs, you can set a JVM parameter that checks for leaked ByteBuf, for this, you should add -Dio.netty.leakDetectionLevel=PARANOID to the startup parameters, or call the method ResourceLeakDetector.setLevel(PARANOID).

How To Write CRUD Unit Tests for Moq and Linq-to-Sql

I am just getting involved in Moq and unit testing, so forgive me if this seems obvious (a quick search through SO didn't show me anything like this).
I have an interface with the following proposed member:
void AddFeed(Feed feed);
That I would like to write a unit test for this functionality. The test class has a Moq Repository declared as follows:
static IFeedRepository MockFeedsRepository(params Feed[] feeds)
{
var mockFeedsRepository = new Moq.Mock<IFeedRepository>();
mockFeedsRepository.Expect(x => x.Feeds).Returns((feeds.AsQueryable));
return mockFeedsRepository.Object;
}
How should the mock repository declaration be modified to include this new desired behavior or should I create a different Moq (and just how would that be done).
My assumption is that after creating the mock, deriving the unit test will be much easier but hints are greatly appreciated.
Many thanks,
KevDog
I'm also assuming that you would use the AddFeed method like this
Feed myNewFeed = new Feed();
feedRepository.Add(myNewFeed);
and that you're not using it like this (which is poor design)
IFeedRepository feedRepository = new FeedRepository();
Feed myNewFeed = new Feed(feedRepository);
...
myNewFeed.Save();
I'm going to guess that you would want to then have a test something like this:
[Test]
public void TheTest()
{
IFeedRepository repository = MockFeedsRepository({feed1, feed2, feed3});
Feed newFeed = new Feed();
repository.Add(newFeed);
Assert.AreEqual(4,repository.Count());
}
If that's the case then the test isn't actually testing anything other than your implementation of a mock in-memory repository. Is that what you really need to be doing?
I'd suggest that what you want to be doing is testing the L2Sql implementation of the repository instead, or testing how classes interact with the IFeedRepository interface.
And if you want to test the usage of the IFeedRepository interface then just do something simple like
[Test]
public void TheTest()
{
IFeedRepository repository = Moq.Mock<IFeedRepository>();
Feed newFeed = new Feed();
repository.Expect(r => r.Add(newFeed)); //no return as it's a void method
//repository.Expect(r => r.Add(newFeed)).Throws(new ApplicationException()); --Test handing of exceptions
//Code to hit the .Add() method
//Assert the Add method was called.
}
For tips on asserting if a method was called, see Using Moq to determine if a method is called
I hope that helps