All topics

Software testing

68 questions, 64 with answers.

  1. What is the difference between integration and unit tests?

    A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.

    Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

    An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.

    Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages. Links

    • https://stackoverflow.com/questions/5357601/whats-the-difference-between-unit-tests-and-integration-tests

    From Java interview (MIT)

  2. Unit test executes code from 2 classes, is it correct? Is it unit or integration test?

    In general, I would say that it's unit tests but with requirements:

    • test executes the logic from one module;
    • test checks only one scenario (in the nested execution there is no branching).

    From Java interview (MIT)

  3. What can be used for unit tests?

    JUnit and TestNG are the main unit test frameworks. Links

    • https://stackoverflow.com/questions/4055957/what-are-the-unit-testing-frameworks-available-in-java

    From Java interview (MIT)

  4. What is better to use randomized or hardcode data for unit tests?

    Avoid randomized data as it can lead to toggling tests which can be hard to debug and omit error messages that make tracing the error back to the code harder.

    Instead, use fixed values for everything. They will create highly reproducible tests, which are easy to debug and create error messages that can be easily traced back to the relevant line of code. Links

    • https://phauer.com/2019/modern-best-practices-testing-java/

    From Java interview (MIT)

  5. Is it possible to test the architecture of application?

    Yes, ArchUnit as example. It does not test your code flow or business logic. The library lets you test your “architecture” including class dependencies, cyclic dependencies, layer accesses, naming conventions, and inheritance checking. Links

    • https://www.freecodecamp.org/news/java-archunit-testing-the-architecture-a09f089585be/
    • https://github.com/TNG/ArchUnit

    From Java interview (MIT)

  6. The differences between Spy and Mock in Mockito?

    When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it.

    On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it. Links

    • https://www.baeldung.com/mockito-spy

    From Java interview (MIT)

  7. How would you assess the quality and effectiveness of unit tests in a Java codebase? Can you explain what mutation testing is and how tools like PIT can help?

    One effective way to assess the quality of unit tests in Java is through mutation testing, which checks whether tests can detect intentional defects. A commonly used tool for this is PIT (Pitest). PIT works by introducing small changes (mutations) to the production code—like flipping conditions or modifying operators—and then running the existing tests. If the tests fail, the mutation is “killed.” If not, it indicates a possible gap in the test’s effectiveness. This approach goes beyond traditional code coverage, focusing on how well tests catch real issues. Links

    • https://pitest.org/

    Home Page

    From Java interview (MIT)

  8. What are the differences between unit tests, integration tests, smoke tests, and regression tests?
    • Unit test: Specify and test one point of the contract of single method of a class. This should have a very narrow and well defined scope. Complex dependencies and interactions to the outside world are stubbed or mocked.

    • Integration test: Test the correct inter-operation of multiple subsystems. There is whole spectrum there, from testing integration between two classes, to testing integration with the production environment.

    • Smoke test (aka sanity check): A simple integration test where we just check that when the system under test is invoked it returns normally and does not blow up.

      • Smoke testing is both an analogy with electronics, where the first test occurs when powering up a circuit (if it smokes, it's bad!)...
      • ... and, apparently, with plumbing, where a system of pipes is literally filled by smoke and then checked visually. If anything smokes, the system is leaky.
    • Regression test: A test that was written when a bug was fixed. It ensures that this specific bug will not occur again. The full name is "non-regression test". It can also be a test made prior to changing an application to make sure the application provides the same outcome.

    To this, I will add:

    • Acceptance test: Test that a feature or use case is correctly implemented. It is similar to an integration test, but with a focus on the use case to provide rather than on the components involved.

    • System test: Tests a system as a black box. Dependencies on other systems are often mocked or stubbed during the test (otherwise it would be more of an integration test).

    • Pre-flight check: Tests that are repeated in a production-like environment, to alleviate the 'builds on my machine' syndrome. Often this is realized by doing an acceptance or smoke test in a production like environment.

    From Stack Overflow: asked by caltuntas, answered by ddaa (CC BY-SA 4.0)

  9. Difference between @Mock and @InjectMocks

    @Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance.

    Note you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4).

    With JUnit 5, you must use @ExtendWith(MockitoExtension.class).

    @RunWith(MockitoJUnitRunner.class) // JUnit 4
    // @ExtendWith(MockitoExtension.class) for JUnit 5
    public class SomeManagerTest {
        @InjectMocks
        private SomeManager someManager;
        @Mock
        private SomeDependency someDependency; // this will be injected into someManager
     
         // tests...
    }
    

    From Stack Overflow: asked by user2249972, answered by Tom Verelst (CC BY-SA 4.0)

  10. What is the difference between 'it' and 'test' in Jest?

    The Jest docs state it is an alias of test. So they are exactly the same from a functional point of view. They exist both to enable to make a readable English sentence from your test.

    From Stack Overflow: asked by C.Lee, answered by musicformellons (CC BY-SA 4.0)

  11. What is Mocking?

    Prologue: If you look up the noun mock in the dictionary you will find that one of the definitions of the word is something made as an imitation.

    Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behaviour of the object you want to test you replace the other objects by mocks that simulate the behaviour 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 behaviour of real objects.

    At times you may want to distinguish between mocking as opposed to stubbing. There may be some disagreement about this subject but my definition of a stub is a "minimal" simulated object. The stub implements just enough behaviour to allow the object under test to execute the test.

    A mock is like a stub but the test will also verify that the object under test calls the mock as expected. Part of the test is verifying that the mock was used correctly.

    To give an example: You can stub a database by implementing a simple in-memory structure for storing records. The object under test can then read and write records to the database stub to allow it to execute the test. This could test some behaviour of the object not related to the database and the database stub would be included just to let the test run.

    If you instead want to verify that the object under test writes some specific data to the database you will have to mock the database. Your test would then incorporate assertions about what was written to the database mock.

    From Stack Overflow: asked by masoud ramezani, answered by Martin Liversage (CC BY-SA 4.0)

  12. What is a reasonable code coverage % for unit tests (and why)?

    This prose by Alberto Savoia answers precisely that question (in a nicely entertaining manner at that!):

    http://www.artima.com/forums/flat.jsp?forum=106&thread=204677

    Testivus On Test Coverage

    Early one morning, a programmer asked the great master:

    “I am ready to write some unit tests. What code coverage should I aim for?”

    The great master replied:

    “Don’t worry about coverage, just write some good tests.”

    The programmer smiled, bowed, and left.

    ...

    Later that day, a second programmer asked the same question.

    The great master pointed at a pot of boiling water and said:

    “How many grains of rice should I put in that pot?”

    The programmer, looking puzzled, replied:

    “How can I possibly tell you? It depends on how many people you need to feed, how hungry they are, what other food you are serving, how much rice you have available, and so on.”

    “Exactly,” said the great master.

    The second programmer smiled, bowed, and left.

    ...

    Toward the end of the day, a third programmer came and asked the same question about code coverage.

    “Eighty percent and no less!” Replied the master in a stern voice, pounding his fist on the table.

    The third programmer smiled, bowed, and left.

    ...

    After this last reply, a young apprentice approached the great master:

    “Great master, today I overheard you answer the same question about code coverage with three different answers. Why?”

    The great master stood up from his chair:

    “Come get some fresh tea with me and let’s talk about it.”

    After they filled their cups with smoking hot green tea, the great master began to answer:

    “The first programmer is new and just getting started with testing. Right now he has a lot of code and no tests. He has a long way to go; focusing on code coverage at this time would be depressing and quite useless. He’s better off just getting used to writing and running some tests. He can worry about coverage later.”

    “The second programmer, on the other hand, is quite experience both at programming and testing. When I replied by asking her how many grains of rice I should put in a pot, I helped her realize that the amount of testing necessary depends on a number of factors, and she knows those factors better than I do – it’s her code after all. There is no single, simple, answer, and she’s smart enough to handle the truth and work with that.”

    “I see,” said the young apprentice, “but if there is no single simple answer, then why did you answer the third programmer ‘Eighty percent and no less’?”

    The great master laughed so hard and loud that his belly, evidence that he drank more than just green tea, flopped up and down.

    “The third programmer wants only simple answers – even when there are no simple answers … and then does not follow them anyway.”

    The young apprentice and the grizzled great master finished drinking their tea in contemplative silence.

    From Stack Overflow: asked by sanity, answered by Jon Limjap (CC BY-SA 3.0)

  13. Unit test naming best practices

    Update (Jul 2021)

    It's been quite a while since my original answer (almost 12 years) and best practices have been changing a lot during this time. So I feel inclined to update my own answer and offer different naming strategies to the readers.

    Many comments and answers point out that the naming strategy I propose in my original answer is not resistant to refactorings and ends up with difficult to understand names, and I fully agree.

    In the last years, I ended up using a more human readable naming schema where the test name describes what we want to test, in the line described by Vladimir Khorikov.

    Some examples would be:

    • Add_credit_updates_customer_balance
    • Purchase_without_funds_is_not_possible
    • Add_affiliate_discount

    But as you can see it's quite a flexible schema but the most important thing is that reading the name you know what the test is about without including technical details that may change over time.

    To name the projects and test classes I still adhere to the original answer schema.

    Original answer (Oct 2009)

    I like Roy Osherove's naming strategy. It's the following:

    [UnitOfWork_StateUnderTest_ExpectedBehavior]

    It has every information needed on the method name and in a structured manner.

    The unit of work can be as small as a single method, a class, or as large as multiple classes. It should represent all the things that are to be tested in this test case and are under control.

    For assemblies, I use the typical .Tests ending, which I think is quite widespread and the same for classes (ending with Tests):

    [NameOfTheClassUnderTestTests]

    Previously, I used Fixture as suffix instead of Tests, but I think the latter is more common, then I changed the naming strategy.

    From Stack Overflow: asked by James Newton-King, answered by Marc Climent (CC BY-SA 4.0)

  14. Can Mockito capture arguments of a method called multiple times?

    I think it should be

    verify(mockBar, times(2)).doSomething(...)
    

    Sample from mockito javadoc:

    ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
    verify(mock, times(2)).doSomething(peopleCaptor.capture());
    List<Person> capturedPeople = peopleCaptor.getAllValues();
    assertEquals("John", capturedPeople.get(0).getName());
    assertEquals("Jane", capturedPeople.get(1).getName());
    

    From Stack Overflow: asked by Eric Wilson, answered by proactif (CC BY-SA 3.0)

  15. Where do the Python unit tests go?

    For a file module.py, the unit test should normally be called test_module.py, following Pythonic naming conventions.

    There are several commonly accepted places to put test_module.py:

    1. In the same directory as module.py.
    2. In ../tests/test_module.py (at the same level as the code directory).
    3. In tests/test_module.py (one level under the code directory).

    I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with test_. Actually, the default unittest pattern used for test discovery is test*.py.

    From Stack Overflow: asked by readonly, answered by user6868 (CC BY-SA 3.0)

  16. Is Unit Testing worth the effort?

    Every day in our office there is an exchange which goes something like this:

    "Man, I just love unit tests, I've just been able to make a bunch of changes to the way something works, and then was able to confirm I hadn't broken anything by running the test over it again..."

    The details change daily, but the sentiment doesn't. Unit tests and test-driven development (TDD) have so many hidden and personal benefits as well as the obvious ones that you just can't really explain to somebody until they're doing it themselves.

    But, ignoring that, here's my attempt!

    1. Unit Tests allows 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.

    A lot of work I'm involved with doesn't Unit Test well (web application user interactions etc.), but even so we're all test infected in this shop, and happiest when we've got our tests tied down. I can't recommend the approach highly enough.

    From Stack Overflow: asked by Ross Fuhrman, answered by reefnet_alex (CC BY-SA 3.0)

  17. What is the difference between unit tests and functional tests?

    Unit tests tell a developer that the code is doing things right; functional tests tell a developer that the code is doing the right things.

    You can read more at Unit Testing versus Functional Testing

    A well explained real-life analogy of unit testing and functional testing can be described as follows,

    Many times the development of a system is likened to the building of a house. While this analogy isn't quite correct, we can extend it for the purposes of understanding the difference between unit and functional tests.

    Unit testing is analogous to a building inspector visiting a house's construction site. He is focused on the various internal systems of the house, the foundation, framing, electrical, plumbing, and so on. He ensures (tests) that the parts of the house will work correctly and safely, that is, meet the building code.

    Functional tests in this scenario are analogous to the homeowner visiting this same construction site. He assumes that the internal systems will behave appropriately, that the building inspector is performing his task. The homeowner is focused on what it will be like to live in this house. He is concerned with how the house looks, are the various rooms a comfortable size, does the house fit the family's needs, are the windows in a good spot to catch the morning sun.

    The homeowner is performing functional tests on the house. He has the user's perspective.

    The building inspector is performing unit tests on the house. He has the builder's perspective.

    As a summary,

    Unit Tests are written from a programmers perspective. They are made to ensure that a particular method (or a unit) of a class performs a set of specific tasks.

    Functional Tests are written from the user's perspective. They ensure that the system is functioning as users are expecting it to.

    From Stack Overflow: asked by mousey, answered by Anthony Forloney (CC BY-SA 4.0)

  18. What does “DAMP not DRY” mean when talking about unit tests?

    It's a balance, not a contradiction

    DAMP and DRY are not contradictory, rather they balance two different aspects of a code's maintainability. Maintainable code (code that is easy to change) is the ultimate goal here.

    DAMP (Descriptive And Meaningful Phrases) promotes the readability of the code.

    To maintain code, you first need to understand the code. To understand it, you have to read it. Consider for a moment how much time you spend reading code. It's a lot. DAMP increases maintainability by reducing the time necessary to read and understand the code.

    DRY (Don't repeat yourself) promotes the orthogonality of the code.

    Removing duplication ensures that every concept in the system has a single authoritative representation in the code. A change to a single business concept results in a single change to the code. DRY increases maintainability by isolating change (risk) to only those parts of the system that must change.

    So, why is duplication more acceptable in tests?

    Tests often contain inherent duplication because they are testing the same thing over and over again, only with slightly different input values or setup code. However, unlike production code, this duplication is usually isolated only to the scenarios within a single test fixture/file. Because of this, the duplication is minimal and obvious, which means it poses less risk to the project than other types of duplication.

    Furthermore, removing this kind of duplication reduces the readability of the tests. The details that were previously duplicated in each test are now hidden away in some new method or class. To get the full picture of the test, you now have to mentally put all these pieces back together.

    Therefore, since test code duplication often carries less risk, and promotes readability, its easy to see how it is considered acceptable.

    As a principle, favor DRY in production code, favor DAMP in test code. While both are equally important, with a little wisdom you can tip the balance in your favor.

    From Stack Overflow: asked by Ian Ringrose, answered by Chris Edwards (CC BY-SA 3.0)

  19. Should I test private methods or only public ones?

    I do not unit test private methods. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation.

    If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there (Method Object). Then I can easily test the previously-private-but-now-public method that now lives on its own class.

    From Stack Overflow: asked by Patrick Desjardins, answered by jop (CC BY-SA 3.0)

  20. What's the best strategy for unit-testing database-driven applications?

    I've actually used your first approach with quite some success, but in slightly different ways that I think would solve some of your problems:

    1. Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge.

    2. Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found until just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but it's not a big deal if someone forgets).

    3. For my group, user input is done at the application level (not db) so this is tested via standard unit tests.

    Loading Production Database Copy:
    This was the approach that was used at my last job. It was a huge pain because of a couple of issues:

    1. The copy would get out of date from the production version
    2. Changes would be made to the copy's schema and wouldn't get propagated to the production systems. At this point we'd have diverging schemas. Not fun.

    Mocking Database Server:
    We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches.

    From Stack Overflow: asked by friedo, answered by Mark Roddy (CC BY-SA 4.0)

  21. NUnit vs. MbUnit vs. MSTest vs. xUnit.net

    I know this is an old thread, but I thought I'd post a vote for xUnit.NET. While most of the other testing frameworks mentioned are all pretty much the same, xUnit.NET has taken a pretty unique, modern, and flexible approach to unit testing. It changes terminology, so you no longer define TestFixtures and Tests...you specify Facts and Theories about your code, which integrates better with the concept of what a test is from a TDD/BDD perspective.

    xUnit.NET is also EXTREMELY extensible. Its FactAttribute and TraitAttribute attribute classes are not sealed, and provide overridable base methods that give you a lot of control over how the methods those attributes decorate should be executed. While xUnit.NET in its default form allows you to write test classes that are similar to NUnit test fixtures with their test methods, you are not confined to this form of unit testing at all. You are free to extend the framework to support BDD-style Concern/Context/Observation specifications, as depicted here.

    xUnit.NET also supports fit-style testing directly out of the box with its Theory attribute and corresponding data attributes. Fit input data may be loaded from excel, database, or even a custom data source such as a Word document (by extending the base data attribute.) This allows you to capitalize on a single testing platform for both unit tests and integration tests, which can be huge in reducing product dependencies and required training.

    Other approaches to testing may also be implemented with xUnit.NET...the possibilities are pretty limitless. Combined with another very forward looking mocking framework, Moq, the two create a very flexible, extensible, and powerful platform for implementing automated testing.

    From Stack Overflow: asked by bitbonk, answered by jrista (CC BY-SA 4.0)

  22. Can Mockito stub a method without regard to the argument?
    when(
      fooDao.getBar(
        any(Bazoo.class)
      )
    ).thenReturn(myFoo);
    

    or (to avoid nulls):

    when(
      fooDao.getBar(
        (Bazoo)notNull()
      )
    ).thenReturn(myFoo);
    

    Don't forget to import matchers (many others are available):

    For Mockito 2.1.0 and newer:

    import static org.mockito.ArgumentMatchers.*;
    

    For older versions:

    import static org.mockito.Matchers.*;
    

    From Stack Overflow: asked by Eric Wilson, answered by Tomasz Nurkiewicz (CC BY-SA 4.0)

  23. Best practices to test protected methods with PHPUnit

    If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:

    protected static function getMethod($name) {
      $class = new ReflectionClass('MyClass');
      $method = $class->getMethod($name);
      // $method->setAccessible(true); // Use this if you are running PHP older than 8.1.0
      return $method;
    }
    public function testFoo() {
      $foo = self::getMethod('foo');
      $obj = new MyClass();
      $foo->invokeArgs($obj, array(...));
      ...
    }
    

    From Stack Overflow: asked by GrGr, answered by uckelman (CC BY-SA 4.0)

  24. Mockito - difference between doReturn() and when()

    The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when for stubbing; but there are cases where you can't use when/thenReturn. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.

    One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.

    I strongly recommend only using doReturn/when. There is no point in learning two syntaxes when one will do.

    You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.

    From Stack Overflow: asked by blackpanther, answered by Dawood ibn Kareem (CC BY-SA 3.0)

  25. How do I test a class that has private methods, fields or inner classes?

    If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.

    Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection.

    Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
    method.setAccessible(true);
    return method.invoke(targetObject, argObjects);
    

    And for fields:

    Field field = TargetClass.getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(object, value);
    

    Notes:

    1. TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField.
    2. The setAccessible(true) is required to play around with privates.

    From Stack Overflow: asked by MattGrommes, answered by Cem Catikkas (CC BY-SA 4.0)

  26. How to mock void methods with Mockito?

    Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

    For example,

    Mockito.doThrow(new Exception()).when(instance).methodName();
    

    or if you want to combine it with follow-up behavior,

    Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
    

    Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

    World mockWorld = mock(World.class); 
    doAnswer(new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) {
          Object[] args = invocation.getArguments();
          System.out.println("called with arguments: " + Arrays.toString(args));
          return null;
        }
    }).when(mockWorld).setState(anyString());
    

    From Stack Overflow: asked by ibrahimyilmaz, answered by sateesh (CC BY-SA 4.0)

  27. How do I generate a stream from a string?
    public static Stream GenerateStreamFromString(string s)
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }
    

    Don't forget to use Using:

    using (var stream = GenerateStreamFromString("a,b \n c,d"))
    {
        // ... Do stuff to stream
    }
    

    About the StreamWriter not being disposed. StreamWriter is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. The Dispose method will close the underlying Stream that StreamWriter is writing to. In this case that is the MemoryStream we want to return.

    In .NET 4.5 there is now an overload for StreamWriter that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.

    See Is there any way to close a StreamWriter without closing its BaseStream?

    From Stack Overflow: asked by Omu, answered by Cameron MacFarland (CC BY-SA 3.0)

  28. Running unittest with typical test directory structure

    The best solution in my opinion is to use the unittest command line interface which will add the directory to the sys.path so you don't have to (done in the TestLoader class).

    For example for a directory structure like this:

    new_project
    ├── antigravity.py
    └── test_antigravity.py
    

    You can just run:

    $ cd new_project
    $ python -m unittest test_antigravity
    

    For a directory structure like yours:

    new_project
    ├── antigravity
    │   ├── __init__.py         # make it a package
    │   └── antigravity.py
    └── test
        ├── __init__.py         # also make test a package
        └── test_antigravity.py
    

    And in the test modules inside the test package, you can import the antigravity package and its modules as usual:

    # import the package
    import antigravity
    # import the antigravity module
    from antigravity import antigravity
    # or an object inside the antigravity module
    from antigravity.antigravity import my_object
    

    Running a single test module:

    To run a single test module, in this case test_antigravity.py:

    $ cd new_project
    $ python -m unittest test.test_antigravity
    

    Just reference the test module the same way you import it.

    Running a single test case or test method:

    Also you can run a single TestCase or a single test method:

    $ python -m unittest test.test_antigravity.GravityTestCase
    $ python -m unittest test.test_antigravity.GravityTestCase.test_method
    

    Running all tests:

    You can also use test discovery which will discover and run all the tests for you, they must be modules or packages named test*.py (can be changed with the -p, --pattern flag):

    $ cd new_project
    $ python -m unittest discover
    $ # Also works without discover for Python 3
    $ # as suggested by @Burrito in the comments
    $ python -m unittest
    

    This will run all the test*.py modules inside the test package.

    Here you can find the updated official documentation of discovery.

    From Stack Overflow: asked by Major Major, answered by Pierre (CC BY-SA 4.0)

  29. Should I intentionally break the build when a bug is found in production?

    Our strategy is:

    Check in a failing test, but annotate it with @Ignore("fails because of Bug #1234").

    That way, the test is there, but the build does not break.

    Of course you note the ignored test in the bug db, so the @Ignore is removed once the test is fixed. This also serves as an easy check for the bug fix.

    The point of breaking the build on failing tests is not to somehow put the team under pressure - it's to alert them to a problem. Once the problem is identified and filed in the bug DB, there's no point in having the test run for every build - you know that it will fail.

    Of course, the bug should still be fixed. But scheduling the fix is a business decision, and thus not really the dev's concern... To me, once a bug is filed in the bug DB, it's no longer my problem, until the customer/product owner tells me they want it fixed.

    From Software Engineering Stack Exchange: asked by MattDavey, answered by sleske (CC BY-SA 3.0)

  30. How do you unit test private methods?

    You generally don't unit test private methods directly. Since they are private, consider them an implementation detail. Nobody is ever going to call one of them and expect it to work a particular way.

    You should instead test your public interface. If the methods that call your private methods are working as you expect, you then assume by extension that your private methods are working correctly.

    From Software Engineering Stack Exchange: asked by Vinoth Kumar C M, answered by Adam Lear (CC BY-SA 3.0)

After the last page: 4 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.