FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

24 Unit Testing Interview Questions (ANSWERED) For Software Developers

Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outputs you'd expect from that. Follow along and check the 24 Most Common and Advanced Unit Testing Interview Questions every experienced developer may be asked on the next tech interview.

Q1: 
How to unit test an object with database queries?

Answer
  • If your objects are tightly coupled to your data layer, it is difficult to do proper unit testing. Your objects should be persistent ignorant. You should have a data access layer, that you would make requests to, that would return objects.
  • Then mock out your calls to the database. This way, you can leave that DB dependants part out of your unit tests, test them in isolation or write integration tests.

Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q2: 
Should unit tests be written for Getter and Setters?

Answer

Properties (getters/setters) are good examples of code that usually doesn’t contain any logic, and doesn’t require testing. But watch out: once you add any check inside the property, you’ll want to make sure that logic is being tested.

In other words, if your getters and setters do more than just get and set (i.e. they're properly complex methods), then yes, they should be tested. But don't write a unit test case just to test a getter or setters, that's a waste of time.


Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q3: 
What is Mocking?

Answer

Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.

In short, mocking is creating objects that simulate the behavior of real objects.


Having Tech or Coding Interview? Check 👉 29 Software Testing Interview Questions

Q4: 
What is the difference between Unit Tests and Functional Tests?

Answer
  • Unit Test - testing an individual unit, such as a method (function) in a class, with all dependencies mocked up.
  • Functional Test - AKA Integration Test, testing a slice of functionality in a system. This will test many methods and may interact with dependencies like Databases or Web Services.

Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q5: 
Can you provide and example of a common Mocking scenario?

Answer

Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to the caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether and just returns a result. That result is typically defined by you ahead of time.

Let look at the mocking out your calls to the database. In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code:

class Bar
{
    private FooDataProvider _dataProvider;

    public instantiate(FooDataProvider dataProvider) {
        _dataProvider = dataProvider;
    }

    public getAllFoos() {
        // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction
        return _dataProvider.GetAllFoos();
    }
}

class FooDataProvider
{
    public Foo[] GetAllFoos() {
        return Foo.GetAll();
    }
}

Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database.

class BarTests
{
    public TestGetAllFoos() {
        // here we set up our mock FooDataProvider
        mockRepository = MockingFramework.new()
        mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider);

        // create a new array of Foo objects
        testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()}

        // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos,
        // instead of calling to the database and returning whatever is in there
        // ExpectCallTo and Returns are methods provided by our imaginary mocking framework
        ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray)

        // now begins our actual unit test
        testBar = new Bar(mockFooDataProvider)
        baz = testBar.GetAllFoos()

        // baz should now equal the testFooArray object we created earlier
        Assert.AreEqual(3, baz.length)
    }
}

Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q6: 
How can I unit test a GUI?

Answer

The answer is to use MVC and move as much logic out of the GUI as possible. For the graphic, you should test the value that you supply to the code that generates the graphic.

I heard from a coworker a long time ago that when SGI was porting OpenGL to new hardware, they had a bunch of unit tests that would draw a set of primatives to the screen and then compute an MD5 sum of the frame buffer. This value could then be compared to known good hash values to quickly determine if the API is per pixel-accurate.


Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q7: 
How would you unit test private methods?

Answer

If you want to unit test a private method, something may be wrong. Unit tests are (generally speaking) meant to test the interface of a class, meaning its public (and protected) methods. You can of course "hack" a solution to this (even if just by making the methods public), but you may also want to consider:

  1. If the method you'd like to test is really worth testing, it may be worth to move it into its own class.
  2. Add more tests to the public methods that call the private method, testing the private method's functionality. (As the commentators indicated, you should only do this if these private methods's functionality is really a part in with the public interface. If they actually perform functions that are hidden from the user (i.e. the unit test), this is probably bad).

Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q8: 
Is writing Unit Tests worth it for already exciting functionality?

Answer

It's absolutely worth it. Our app has complex cross-validation rules, and we recently had to make significant changes to the business rules. We ended up with conflicts that prevented the user from saving. I realized it would take forever to sort it out in the application (it takes several minutes just to get to the point where the problems were). I'd wanted to introduce automated unit tests and had the framework installed, but I hadn't done anything beyond a couple of dummy tests to make sure things were working. With the new business rules in hand, I started writing tests. The tests quickly identified the conditions that caused the conflicts, and we were able to get the rules clarified.

If you write tests that cover the functionality you're adding or modifying, you'll get an immediate benefit. If you wait for a re-write, you may never have automated tests.

You shouldn't spend a lot of time writing tests for existing things that already work. Most of the time, you don't have a specification for the existing code, so the main thing you're testing is your reverse-engineering ability. On the other hand, if you're going to modify something, you need to cover that functionality with tests so you'll know you made the changes correctly. And of course, for new functionality, write tests that fail, then implement the missing functionality.


Having Tech or Coding Interview? Check 👉 29 Software Testing Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
Name some Unit Testing benefits for devs that you personally experienced

Answer
  1. Unit Tests allow you to make big changes to code quickly. You know it works now because you've run the tests, when you make the changes you need to make, you need to get the tests working again. This saves hours.

  2. TDD helps you to realise when to stop coding. Your tests give you confidence that you've done enough for now and can stop tweaking and move on to the next thing.

  3. The tests and the code work together to achieve better code. Your code could be bad / buggy. Your TEST could be bad / buggy. In TDD you are banking on the chances of both being bad / buggy being low. Often it's the test that needs fixing but that's still a good outcome.

  4. TDD helps with coding constipation. When faced with a large and daunting piece of work ahead writing the tests will get you moving quickly.

  5. Unit Tests help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outputs you'd expect from that.

  6. Unit Tests give you instant visual feedback, we all like the feeling of all those green lights when we've done. It's very satisfying. It's also much easier to pick up where you left off after an interruption because you can see where you got to - that next red light that needs fixing.

  7. Contrary to popular belief unit testing does not mean writing twice as much code or coding slower. It's faster and more robust than coding without tests once you've got the hang of it. Test code itself is usually relatively trivial and doesn't add a big overhead to what you're doing. This is one you'll only believe when you're doing it :)

  8. I think it was Fowler who said: "Imperfect tests, run frequently, are much better than perfect tests that are never written at all". I interpret this as giving me permission to write tests where I think they'll be most useful even if the rest of my code coverage is woefully incomplete.

  9. Good unit tests can help document and define what something is supposed to do

  10. Unit tests help with code re-use. Migrate both your code and your tests to your new project. Tweak the code till the tests run again.


Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q10: 
Should I Unit Test private methods or only public ones?

Answer

In general, you don't want to break any encapsulation for the sake of testing (or as Mom used to say, "don't expose your privates!"). Most of the time, you should be able to test a class by exercising its public methods. If there is significant functionality that is hidden behind private or protected access, that might be a warning sign that there's another class in there struggling to get out.

You might not like testing private functionality for a couple of reasons:

  1. Typically when you're tempted to test a class's private method, it's a design smell.
  2. You can test them through the public interface (which is how you want to test them, because that's how the client will call/use them). You can get a false sense of security by seeing the green light on all the passing tests for your private methods. It is much better/safer to test edge cases on your private functions through your public interface.
  3. You risk severe test duplication (tests that look/feel very similar) by testing private methods. This has major consequences when requirements change, as many more tests than necessary will break. It can also put you in a position where it is hard to refactor because of your test suite...which is the ultimate irony, because the test suite is there to help you safely redesign and refactor!

Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q11: 
What do I lose by adopting TDD? What are the disadvantages of Test Driven Development?

Answer
  • Big-time investment + knowledge required of knowing how to write testable code.. For the simple case, you lose about 20% of the actual implementation, but for complicated cases, you lose much more.
  • Where you have a large number of tests, changing the system might require re-writing some or all of your tests, depending on which ones got invalidated by the changes. This could turn a relatively quick modification into a very time-consuming one.
  • You might start making design decisions based more on TDD than on actually good design principles. As a result, you now have a much more complex system that is actually more prone to mistakes (and other devs and devs after you shall know how to support it).
  • Complexity of code (DI, IoC, MVC/MVP__) + Design Impacts. When you start using mocks, after a while, you will want to start using Dependency Injection (DI) and an Inversion of Control (IoC) container. To do that you need to use interfaces for everything (which have a lot of pitfalls themselves). At the end of the day, you have to write a lot more code, than if you just do it the "plain old way". Instead of just a customer class, you also need to write an interface, a mock class, some IoC configuration and a few tests.
  • Prototyping can be very difficult with TDD. Continuous Tweaking of tests in the exploration phase of the project. For data structures and black-box algorithms, unit tests would be perfect, but for algorithms that tend to be changed, tweaked or fine-tuned, this can cause a big-time investment that one might claim is not justified. Every time you change the design of a class, now you have to also change the test cases.

Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q12: 
What is a reasonable Code Coverage % for unit tests (and why)?

Answer

Code coverage is great, but functionality coverage is even better. I don't believe in covering every single line I write. But I do believe in writing 100% test coverage of all the functionality I want to provide (even for the extra cool features I came with myself and which were not discussed during the meetings).

I don't care if I would have code which is not covered in tests, but I would care if I would refactor my code and end up having a different behaviour. Therefore, 100% functionality coverage is my only target.


Having Tech or Coding Interview? Check 👉 29 Software Testing Interview Questions

Q13: 
What is the fundamental value of Unit Tests vs Integration Tests?

Answer
  • Integration tests tell what's not working. But they are of no use in guessing where the problem could be.
  • Unit tests are the sole tests that tell you where exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.

Consider:

A single bug will break several features, and several integration tests will fail.

On the other hand, the same bug will break just one unit test.


Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q14: 
What's the difference between Mock an object or Spy on it?

Answer
  • Mock object replace mocked class entirely, returning recorded or default values. You can create a mock out of thin air. This is what is mostly used during unit testing.
  • When spying, you take an existing object and replace only some methods. This is useful when you have a huge class and only want to mock certain methods (partial mocking). We spy real objects meaning that we can instruct which method to be stubbed. In a nutshell, you will spy real object and stub some of the methods.

When in doubt, use mocks.


Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions

Q15: 
When and where should I use Mocking?

Answer

Rule of thumb:

If the function you are testing needs a complicated object as a parameter, and it would be a pain to simply instantiate this object (if, for example, it tries to establish a TCP connection), use a mock. Mock objects allow you to set up test scenarios without bringing to bear large, unwieldy resources such as databases. Mock objects are simulated objects that mimic the behaviour of real objects in controlled ways.

Typically you write a mock object if:

  • The real object is too complex to incorporate it in a unit testing (For example a networking communication, you can have a mock object that simulate been the other peer)
  • The result of your object is non-deterministic
  • The real object is not yet available

For example:

Let's say we want to test that method sendInvitations(MailServer mailServer) calls MailServer.createMessage() exactly once, and also calls MailServer.sendMessage(m) exactly once, and no other methods are called on the MailServer interface. This is when we can use mock objects.

With mock objects, instead of passing a real MailServerImpl, or a test TestMailServer, we can pass a mock implementation of the MailServer interface. Before we pass a mock MailServer, we train it, so that it knows what method calls to expect and what return values to return. In the end, the mock object asserts, that all expected methods were called as expected.

Note:

A Unit Test should test a single code path through a single method. When the execution of a method passes outside of that method, into another object, and back again, you have a dependency.

When you test that code path with the actual dependency, you are not unit testing; you are integration testing. While that's good and necessary, it isn't unit testing.


Having Tech or Coding Interview? Check 👉 24 Unit Testing Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
Can Unit Testing be successfully added into an existing production project? If so, how and is it worth it?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q17: 
Explain what is Arrange-Act-Assert pattern?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q18: 
What are best practices for Unit Testing methods that use cache heavily?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q19: 
What is Unit test, Integration Test, Smoke test, Regression Test and what are the differences between them?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q20: 
What is the best way to unit test a method that doesn't return anything (void)?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q21: 
What's the best strategy for Unit-Testing database-driven applications?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q22: 
What's the difference between Faking, Mocking, and Stubbing?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q23: 
How do I test a private function or a class that has private methods, fields or inner classes?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q24: 
Is Unit Testing worth the effort?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...