How To Write Test Case For Catch Exception In Junit Mockito

Thanks Frank, I have gone through the Junit test cases in the sample application provided with the post in the thread. Testing for Exceptions. Unit Tests Using JUnit alone. Why Drink Mockito? Mockito is an easy-to-use, open source mocking library. com/learn/Spring5 Spring Full Course (UD. In your test you have commented out the line that returns the mock FileStatus. How do I execute only one feature file out of many?. To use Mockito like this in a ScalaTest project, the first step is to include the Mockito JAR file in your project. This will increase the test coverage also. exec binary file. , the class—you will probably use Mockito alone. Learn how to use Test Driven Development (TDD) and apply Unit Testing using Junit and Mockito for Android Development 3. method // method that I want to fake the return value // some code that I still want to run } }. This book will provide the skills you need to successfully build and maintain meaningful JUnit test cases. The canonical reference for building a production grade API with Spring. In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):. Reference: org. Run Test case (or Test Suite) : To run a test case (or test suite), right-click the file ⇒ Run As ⇒ JUnit Test. There was a code that used System static methods directly and needed testing. I have a problem with the Mocking Framework Mockito. The procedure is to write test cases for all functions and methods so that whenever a change causes a fault. 8 to JUnit 4. Learn how to use Test Driven Development (TDD) and apply Unit Testing using Junit and Mockito for Android Development 3. Mock internal method with JUnit and Mockito. This test does however utilize JUnit's "expected" option telling the test to expect a certain type of exception. You really should avoid such design choices, and choose other alternatives. And the latter just lets the test fail in case of an exception which is exactly what you want. In this tutorial you will create a web application with an entity class and a session bean. Mockito framework is what I use for just this and in this post we’ll see how to use mockito effectively to mock those dependencies. Occasionally, you might want to verify in your unit test that a method throws some specific exception. Testing for Exceptions. Normally I would use a mocking framework like Mockito to reach this. If you want to cover the code in the catch block, your test needs to cause an exception to be thrown in the try block. At the time of writing, JUnit has bifurcated into JUnit 4 and JUnit 5. TestNG has provided an ability to implement 'IReporter' an interface which can be implemented to generate a customized report by users. Read on for the. Mockito is used for mocking the java objects and then the objects are injected into the java classes which uses them. Your tests should be stored in the src/test directory. 18 May 2009 1. Junit doesn’t only intend to ensure that code is working as expected and validate that this is still the case after code changes, it’s also capable for testing method which expects to throw desired exception. class using mockito in a junit test. I was writing Junit tests and I was told to have good coverage. When checked JACOCO test coverage. It is unnecessary to write your own catch blocks that exist only to pass a test because the. I have written Junit test case for following function. Get Acquainted with the New Advanced Features of JUnit 4 : Page 2 Learn how to migrate from JUnit 3. Mockito is distributed. We can use Mockito mock objects with when() and thenThrow() to mock this scenario. assertThrows() method. I have a server/client application and want to use junit to test it. class) is used to provide a bridge between Spring Boot test features and JUnit. Learn Unit Testing with Junit & Mockito in 30 Steps 4. Erich Gamma and Kent Beck initially develop it. m(0); You want to check in a JUnit 5 testing procedure that the call throws the exception. Take a look at the following code snippet. The core idea of unit tests is to test a unit of code in isolation from any of its dependencies. Anypoint is nothing but eclipse with some extra features and a UI for coding. unittest provides a base class, TestCase, which may be used to create new test cases. Occasionally, you might want to verify in your unit test that a method throws some specific exception. Mockito - mock for Context and getApplicationContext() Just started creating UTs for my app and using PowerMock, Mockito and Junit4. This book explains in detail how to implement unit tests using two very popular open source Java technologies: JUnit and Mockito. Mockito is an Open Source framework for Java that allows you to easily create test doubles or mocks. 2 MVC application. While JUnit 5 has a richer feature set, JUnit 4 is still more popular, and we are more likely to find JUnit 4 test cases in. However, an object under test might have dependencies on other objects. com/learn/Spring5 Spring Full Course (UD. Using JUnit Rules! The Basics Well, before we learn all that, let’s start with the basics, shall we? Timeouts Let’s take a simple example: Suppose that you want to set a timeout for all test methods in a given class, an easy way to do that is like this:. In this post, I explain how to test the side-effects of the code, how to mock Java objects in tests, use mocks in JUnit, and isolate your JUnit tests from the other components in your system. We have verified the call that we are looking for but if tomorrow I change the source code by adding one more call to service the test would not break. getMessage()) To check that exception was thrown for a right reason. I have a server/client application and want to use junit to test it. In the past, I have shared some great books to learn unit testing in Java and today, I am going to share some of the online courses you can use to learn JUnit 5 or Jupiter, the latest version of JUnit library, and Mockito to write a unit test for your Java application. Mockito is distributed. JUnit 4 provides more elegant way to test such exceptional cases. It's too much work to test a simple method, cause developers skipping the test. We’ve just summarized the summary of the steps that you can use to generate reports using the JUnit plugin. Unit tests should be small tests (atomic), lightweight, and fast. Maven junit. java in C:\>JUNIT_WORKSPACE, which is a POJO class. I am new to Mockito. In this short tutorial, we focus on mocking void methods with Mockito. Then we use this runner with the @RunWith annotation which will register our JUnit Listener to the test case. By convention, I’m naming my Integration Test with the suffix of ‘IT’. Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine. You can use junit or testNg unit testing framework to write your test cases. Catch and Resolve. It is very powerful and easy to use. 6 (27 ratings) Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately. 18 May 2009 1. The primary purpose of unit tests it to catch regression errors. This article will look at configuring integration tests using Spring and DBUnit so that test data is inserted into the database before every test. Of course, if you need to test for multiple exceptions within the same test method, the first way won't work. ArgumentCaptor is used with Mockito verify() methods to get the arguments passed when any method is called. Hope you get your answer. assertEquals() example. I am using Cucumber Java to write tests. But maybe in your case its enough to pass an invalid filename. Mockito Expect an Exception. In that case, we would force findCurrentJobPosition() to return an empty Optional. We can add this listener by creating a custom Runner. In this article, I show how you can still thoroughly test components that would usually require integration testing using regular, basic JUnit tests. build() The first approach will automatically load the Spring configuration and inject WebApplicationContext into the test. The Mockito JUnit runner is a plug-in for JUnit which takes away the boilerplate of setting up test objects with mocks. I have a problem with the Mocking Framework Mockito. public ActionForward execute(ActionMapping. Testing with Mockito Mocks. with this post you can write test code for Vertical Scroll up to specified dimensions , Vertical Scroll till you find the element and vertical scroll till the end. Instead, tests can be organised by dividing top level test cases into sections. How do I execute only one feature file out of many?. 4 Click on the arrow of the icon in the toolbar. It checks for a specific response to a particular set of inputs. Background. Exercise: Write an instrumented unit test using Mockito 12. This unit test needs setup of test data such that it covers all the possible scenarios including exception edge case. Mockito (or any other mocking tool) is a framework that you specifically use to efficiently write certain kind of tests. The code shown in examples below is available in GitHub java-samples/junit repository. In JUnit 3. Practical Unit Testing: JUnit, Mockito, TestNG, AssertJ - book by Tomek Kaczanowski Nowadays developers are expected to write unit tests. This post is a kind of basic tutorial to implement JUnit test on your Spring MVC controllers. It might need to interact with a database, communicate with a mail server, or talk to a web service or a message queue. Such naming is especially helpful if you write. How Do I Get Started? Read ten reasons why Spock is for you, run your first spec in Spock Web Console , fork the spock-example project, learn how to write a specification, or dive into the reference documentation. webAppContextSetup(webApplicationContext). When we write Junit test cases or classes, we generally do not test on real object that are injected into the class that has to be tested using Junit to avoid any test case failure at some point, instead we want to test the business logic out of the written code. In this video I will show how to write JUnit test cases with mock objects using mockito framework. Explore Mockito's facilities for dependency injection of mocks. When dealing with a void method in EasyMock, you have to use expectLastCall() to set expectations on it, like throwing an exception in this case. It must also use the @Config() to point to your BuildConfig. One project is for JUnit, the other project is for TestNG. Spock is inspired from JUnit, RSpec, jMock, Mockito, Groovy, Scala, Vulcans, and other fascinating life forms. You use an assert method, provided by JUnit or another assert framework, to check an expected result versus. This post is part of PowerMock series examples. A test that fails is a test that works. JUnit is a framework that helps with writing and running your unit tests. As a result, Mockito helps you build maintainable, high-quality tests that enable continuous delivery. Create an Android application with the package name com. Third testcase gets pass because, it was expecting the NullPointerException and testcase threw it. Start the name of the test case class with the prefix Test B. The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. I am using Mockito. @ Test expected attribute. TestCase − Contains a test case that defines the fixture to run multiple tests. In this video we will see how to write a Test Case for a method that can throw a Exception. But I dont know how to write a Mockito. Here is a method. In part 2 of my tutorial series on unit testing with JUnit I'll take a deeper look at JUnit Assertions, JUnit Annotations, and JUnit Test Suites. When we are testing one unit (NumberAdder in this case) all other classes which NumberAdder. And the latter just lets the test fail in case of an exception which is exactly what you want. Don't be too shy about coding a simple test case for a minor thing. In unit tests, all external dependencies of the subject under the test should be mocked. Then we use this runner with the @RunWith annotation which will register our JUnit Listener to the test case. Occasionally, you might want to verify in your unit test that a method throws some specific exception. Getting started To take advantage of the integration, the Mockito's mockito-junit-jupiter dependency is required to be added next to the JUnit 5's junit-platform-engine one (see below for details). Exception Testing with JUnit. When you write a separate suite to execute the test cases in order, you might feel pain in the neck when you try to add every testXXX() method to the suite, esp. However, I do think that this pattern can be easily overused, so each use should be closely examined to make sure there's not a better way to handle it. In order to explain the title problem better, I shall start by answering the question of when and why to test negative cases. A set of assertion methods useful for writing tests. The JUnit framework will make sure that this test fails if any exception occurs during the invocation of the method under test - there's no need to write your own exception handling. In the first place, I’d forgotten how much I loathe java’s checked exceptions, for all of the reasons I always did previously and now for a new one — they’re a headache with TDD. In Mockito, we mock behavior, not implementation by adding a dummy functionality to a mock interface that can be used in unit testing. Meeting a class requirement sounds like a good reason to backport. In order to create a readable, maintainable, useful test suite, we need to change our testing habits. JUnit is an open source Unit Testing Framework for JAVA. In junit tests, we will configure the spring context programmatically and then will access the users by username from default user details service. Unit tests should not catch exceptions just to call fail(). Or if the execution time of this test is too long to be included. I mock ThirdPartyPluginLicenseStorageManager and PluginLicense. Assertion method Assert. Mockito is used for mocking the java objects and then the objects are injected into the java classes which uses them. A test failure on these tests implies that program behaviour is not as expected by the tests. If you are creating an instrumented JUnit 4 test class to run on a device or emulator, your test class must be prefixed with the @RunWith(AndroidJUnit4. The problem of this approach is this: The problem of this approach is this: If we want to write assertions for the exception thrown by the tested code, we have to capture it first. The above approach is useful for simple cases, but it has its limits. While JUnit 5 has a richer feature set, JUnit 4 is still more popular, and we are more likely to find JUnit 4 test cases in. I have a problem with the Mocking Framework Mockito. We use Hamcrest matchers when we are writing assertions for the responses. We just write Gherkin test cases. RELEASE The relevant part of our pom. This tutorial shows how to Unit Test JPA with JUnit and a H2 In Memory Database. Program: How to do JUnit test for comapring two list of user defined objects? Java Class: org. Demo of testing static methods using JUnit. Mockito Stub Exception - JUnit 5 Let's see a simple example where we will mock our object method to throw an exception. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. The code shown in examples below is available in GitHub java-samples/junit repository. Writing readable tests is at least as important as writing readable production code. There are other ways for junit 5 exception testing, but I will suggest to avoid them. If you solve the first problem by consistently not using new in the throw (and therefore consistently not using delete in the catch), then you probably won’t be able to allocate your exception objects as locals (since then they might get destructed too early), in which case you’ll have to worry about thread-safety, locks, semaphores, etc. But while calling the internal methods of them it. Testing Custom Exceptions With JUnit's ExpectedException and @Rule expected behavior and then catch the exception looking for the specific type. Using assertThrows annotation. What is mockito? Mockito is a mocking framework that tastes really good. In junit tests, we will configure the spring context programmatically and then will access the users by username from default user details service. This unit test needs setup of test data such that it covers all the possible scenarios including exception edge case. 8 to JUnit 4. All the Mockito matchers are a part of ‘Mockito’ static class. I hope you find this tutorial useful. JUnit Tutorial 06 :- Testing Exceptions using JUnit Catching and Handling Exceptions in Java. In Guice, the class would like like this:. We could write a unit test to check, if the conversion works correctly. Matchers are a powerful tool, which enables a shorthand way of setting up stubs as well as verifying invocations on the stubs by mentioning argument inputs as generic types to specific values depending on the use-case or scenario. When we are testing one unit (NumberAdder in this case) all other classes which NumberAdder. In this in-depth hands-on tutorial on How to Write Test Cases, I have covered the details of what is a Test Case, Its standard definition and Test Case Design techniques. Hi, I'm writing Junit test cases for my servlets. JUnit 4 introduced theexpected parameter, which makes a test succeed if and only if a certain exception is thrown. Experience in JUnit framework with Mockito, and Easy mock. If You are writing tests (and I believe that You do) , then You propably already faced a problem with testing a class which has some non-public members. To unit test the functionality of this method, we need to mock the external Product and ProductRepository objects. Assertion method Assert. You can run this test by clicking the green icon located next to the method name. Doing so marks the class as a test case so that you can easily recognize test classes and possibly filter them in build scripts. In this video will will see JUnit Mockito example We will learn : What is JUnit Why do we need JUnit What is Mockito Why to use Mockito How to build JUnit test case Verify Java Code Trainer: Navin. Sometimes, a test method can test more than one method in the target class, and sometimes, if the method to test is big, you split the test into multiple test methods. If you do, what are the tools you need, and is it really necessary to test a web application if doesn't need scaling. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Practical Unit Testing with JUnit and Mockito [Tomek Kaczanowski] on Amazon. Mobile Testing: Automated Testing for Android with Robotium Robotium is a test framework created to make it easy to write powerful and robust automatic black-box test cases for Android applications so test developers don’t need any further information about the Android app’s structure or implemented classes. In this video I will show how to write JUnit test cases with mock objects using mockito framework. Exercise: Write an instrumented unit test using Mockito 12. The call to writeBody should fail to write the body text, catch the exception and return a status indicating that it has failed. This document presents two Maven example projects for mocking final and static methods using PowerMockito for Java unit testing. Let’s assume the following setup: Our unit under test is the class Calculator which just delegates the addition of two integers to MathUtil which offers only static methods:. As of Java 8 we have another way of dealing with exceptions: with lambda expressions, that make catch-exception library redundant. This article introduces jWebUnit, a set of Java classes that you can use to develop test cases for Web applications. Each test method usually tests a single method of the target class. Also, you can annotate a class containing test methods with @Ignore and none of the containing tests will be executed. Such naming is especially helpful if you write. As you can see in the following. There is no need to create a “test fixture” class (although that is supported too). Coming to the testing part, let’s take up the getProductById() method of ProductServiceImpl. robot - Expecting Exceptions JUnit Rule. JUnit 5 has native support for parameterizing test methods as well as an extension point that allows third-party variants of the same theme. Next we will create a JUnit test class for Sequential. com/learn/Spring5 Spring Full Course (UD. In this tutorial, we are going to write JUnit test cases for the Spring Boot controller. java MathApplicationTester. Why do we use JUnit testing? JUnit testing is used to test the behavior of methods inside classes we have written. 11 at the time of writing), there are two more options available to you: the @Test annotation and the ExpectedException rule. This unit test needs setup of test data such that it covers all the possible scenarios including exception edge case. PowerMockito is a PowerMock’s extension API which supports Mockito. We will use the latter option since it is convenient when you have a lot of mocks to inject. The first thing we have to do on our Java…. Sometimes our methods throw exceptions and we want to mock the object and test the exceptions. The release of the Spring MVC Test framework gave us the possibility to write unit tests which are readable, comprehensive and fast. , restructuring a unit’s code but without meaning to change its behaviour. getPrincipal(); return applicationUser; }. com/public/mz47/ecb. Exception Testing with JUnit. Note that in many cases, ignoring the exception may be. List of JUnit annotations. In Guice, the class would like like this:. The test jobs can be grouped into a "test suite" which is a parent job that will call the test jobs with a tRunJob. Side effects from other classes or the system should be eliminated for. Pattern is: Call method. 5 Courses to Learn JUnit and Mockito in 2019 — Best of Lot Don’t avoid unit testing due to initial hiccups, these courses will help you to overcome those. Definitely with the help of Mockito you can do everything you wish in the testing. In this example we will show you how you can add a JUnit Listener to your test cases. The above approach is useful for simple cases, but it has its limits. ) of class org. This post is a kind of basic tutorial to implement JUnit test on your Spring MVC controllers. The code shown in examples below is available in GitHub java-samples/junit repository. To execute Selenium WebDriver testing using JUnit we have to add JUnit annotations in your test. Every test case we will write will be represented by a public void method with the JUnit "@Test" annotation. Introduction. Download CppUnit - C++ port of JUnit for free. Let's see the syntax of assertThrows in JUnit 5. This approach to testing exceptions in JUnit code is a really simple, built-in, not much code but… We need to be quite careful about using @Test annotation: there is way to verify the message or the cause which may lead to quite unexpected behaviour like in the misleading method in the above example. We just write Gherkin test cases. JUnit is an open source Unit Testing Framework for JAVA. catch (Exception e). The procedure is to write test cases for all functions and methods so that whenever a change causes a fault. It provides a testing framework that allows you to add small testing methods to your programs, which the framework will find and run automatically. Sabrina, Yes, using try/catch to test exceptions is a common pattern in JUnit 3. Below is my scenario. Testing for Exceptions. In this post we’ll look at how to write parameterized tests – creating an extension will be left for the future. A test failure on these tests implies that program behaviour is not as expected by the tests. JUnit4 address this issue and provides an easy, and readable way to te st exception thrown by a Java method. JUnit 5 – Parameterized Tests. In addition to Mockito, you will also need to configure the testing dependencies for your project to use the standard APIs provided by the JUnit 4 framework. Test Exception in JUnit 5 - using assertThrows() method JUnit 5 provides the assertThrows() method that asserts a piece of code throws an exception of an expected type and returns the exception: assertThrows(Class expectedType, Executable executable, String message). Assume that we have a class called User Service which does save, get, remove and update operation on DB. If you want to change one of Jemmy's timeouts, do. In our case it could also be an exception from the name validation and initial test won't see the difference! #4. How to write effective PHPUnit test cases; How to test angular directive scope; How to test non-public methods? Testing Ember. A test suite is a collection of test cases, test suites, or both. Suppose a method is supposed to throw an exception. I did actually catch a unit test flu long before I had heard of JUnit or read Test Infected. You should also write tests for unusual conditions, such as a null person reference or null data within the person. However, I do think that this pattern can be easily overused, so each use should be closely examined to make sure there's not a better way to handle it. It lets you write beautiful tests with a clean & simple API. java MathApplication. Practical Unit Testing: JUnit, Mockito, TestNG, AssertJ - book by Tomek Kaczanowski Nowadays developers are expected to write unit tests. xml file looks as follows: Note: If you have to use Spring Framework 3. public ResultSet recentSubmission(). build() The first approach will automatically load the Spring configuration and inject WebApplicationContext into the test. Before Mockito 2, we were required to mock the call to that method:. Try/Catch Idiom. This unit test needs setup of test data such that it covers all the possible scenarios including exception edge case. The naming convention isn’t required, but by doing so, we mark the class as a test case so that we can easily rec-ognize test classes and possibly filter them in build scripts. Mockito is used for mocking the java objects and then the objects are injected into the java classes which uses them. 1 * * This generated file contains a commented-out sample Java project to get you started. We will understand and implement the below topics. Definitely with the help of Mockito you can do everything you wish in the testing. Testing and Generating Test Report Testing as Junit Test. Will ignore the test method. If we had special logic handling DAO exceptions then I would use the “thenThrow()” in mockito and test accordingly. class) telling PowerMock to get inside PowerMockDemo class and prepare it for mocking. I have written Junit test case for following function. For this purpose, I am using PowerMockito framework. Read more about features & motivations. You can even nest sections within each other, or use the BDD style bindings that give you GIVEN-WHEN-THEN blocks. In PyUnit, test cases are represented by the TestCase class in the unittest module. It checks for a specific response to a particular set of inputs. You'll only get coverage for the exception block if an exception is thrown. JUnit4 - Parameterized tests Often times we need to test a single method with several different test data or inputs and Parameterized tests are very useful to maintain a very clean and readable tests in such cases. When we are testing one unit (NumberAdder in this case) all other classes which NumberAdder. Of course, if you need to test for multiple exceptions within the same test method, the first way won't work. Call TestCase. Here I am using AemContext (io. This tutorial assumes that you are familiar with Android programming in general. GridParallelTest class is our test class and it extends GridParallelTestBase class. JUnit Test Runner Class Create a new Class file in the ‘ cucumberTest ‘ package and name it as ‘ TestRunner ‘, by right click on the Package and select New > Class. Both describe methods that implement test cases. Some of the important classes are − Assert − Contains a set of assert methods. In Mockito, we mock behavior, not implementation by adding a dummy functionality to a mock interface that can be used in unit testing. Chose any IDE as eclipse or NetBean 2. However, an object under test might have dependencies on other objects. Suppose MathApplication should call the CalculatorService. I mock ThirdPartyPluginLicenseStorageManager and PluginLicense. In order to create a readable, maintainable, useful test suite, we need to change our testing habits. To test that exceptions are thrown when they should, almost everyone prefers to use JUnit’s annotation argument expected to the good old-fashioned try-catch-with-fail, but in Scala there’s a. At the time of writing, JUnit has bifurcated into JUnit 4 and JUnit 5. Matchers are a powerful tool, which enables a shorthand way of setting up stubs as well as verifying invocations on the stubs by mentioning argument inputs as generic types to specific values depending on the use-case or scenario. When checked JACOCO test coverage. Each is the de facto standard unit testing framework for its respective language. The general wisdom is that your code should be mostly tested with unit tests, but should also have some functional tests. To make sure that the provided name of a mock is included in the message of an exception thrown from an unsuccessful verification, we will rely on a JUnit implementation of the TestRule interface, called ExpectedException, and include it in a test class: @Rule public ExpectedException thrown = ExpectedException. Running tests from within Eclipse. Unit Testing and Mockito Tutorial. The canonical reference for building a production grade API with Spring. Assuming you’re using SBT, either add the Mockito JAR file to your project’s lib directory, or add Mockito as a dependency in your build. 3) Since we are going to develop all our examples using the Mockito extension and JUnit test framework, download the powermock-mockito-junit-1. 2 version and. unittest provides a base class, TestCase, which may be used to create new test cases. So instead of, for example, having to contrive a way to get your RegistrationService to throw a NumberFormatException to test that code path,. TimeoutExpiredException with some included diagnostic test. Notice: Undefined index: HTTP_REFERER in /home/forge/theedmon. A lot of us have been writing unit tests for a long time, most using JUnit or a similar suite, so to many of us it's kind of second nature. This JUnit Listener can listen to events of JUnit lifecycle. The method used for this is thenThrow(. Mockito or Easymock help you mock these dependencies. Stubs – is an object that has predefined return values to method executions made during the test. The fact-checkers, whose work is more and more important for those who prefer facts over lies, police the line between fact and falsehood on a day-to-day basis, and do a great job. Today, my small contribution is to pass along a very good overview that reflects on one of Trump’s favorite overarching falsehoods. Namely: Trump describes an America in which everything was going down the tubes under  Obama, which is why we needed Trump to make America great again. And he claims that this project has come to fruition, with America setting records for prosperity under his leadership and guidance. “Obama bad; Trump good” is pretty much his analysis in all areas and measurement of U.S. activity, especially economically. Even if this were true, it would reflect poorly on Trump’s character, but it has the added problem of being false, a big lie made up of many small ones. Personally, I don’t assume that all economic measurements directly reflect the leadership of whoever occupies the Oval Office, nor am I smart enough to figure out what causes what in the economy. But the idea that presidents get the credit or the blame for the economy during their tenure is a political fact of life. Trump, in his adorable, immodest mendacity, not only claims credit for everything good that happens in the economy, but tells people, literally and specifically, that they have to vote for him even if they hate him, because without his guidance, their 401(k) accounts “will go down the tubes.” That would be offensive even if it were true, but it is utterly false. The stock market has been on a 10-year run of steady gains that began in 2009, the year Barack Obama was inaugurated. But why would anyone care about that? It’s only an unarguable, stubborn fact. Still, speaking of facts, there are so many measurements and indicators of how the economy is doing, that those not committed to an honest investigation can find evidence for whatever they want to believe. Trump and his most committed followers want to believe that everything was terrible under Barack Obama and great under Trump. That’s baloney. Anyone who believes that believes something false. And a series of charts and graphs published Monday in the Washington Post and explained by Economics Correspondent Heather Long provides the data that tells the tale. The details are complicated. Click through to the link above and you’ll learn much. But the overview is pretty simply this: The U.S. economy had a major meltdown in the last year of the George W. Bush presidency. Again, I’m not smart enough to know how much of this was Bush’s “fault.” But he had been in office for six years when the trouble started. So, if it’s ever reasonable to hold a president accountable for the performance of the economy, the timeline is bad for Bush. GDP growth went negative. Job growth fell sharply and then went negative. Median household income shrank. The Dow Jones Industrial Average dropped by more than 5,000 points! U.S. manufacturing output plunged, as did average home values, as did average hourly wages, as did measures of consumer confidence and most other indicators of economic health. (Backup for that is contained in the Post piece I linked to above.) Barack Obama inherited that mess of falling numbers, which continued during his first year in office, 2009, as he put in place policies designed to turn it around. By 2010, Obama’s second year, pretty much all of the negative numbers had turned positive. By the time Obama was up for reelection in 2012, all of them were headed in the right direction, which is certainly among the reasons voters gave him a second term by a solid (not landslide) margin. Basically, all of those good numbers continued throughout the second Obama term. The U.S. GDP, probably the single best measure of how the economy is doing, grew by 2.9 percent in 2015, which was Obama’s seventh year in office and was the best GDP growth number since before the crash of the late Bush years. GDP growth slowed to 1.6 percent in 2016, which may have been among the indicators that supported Trump’s campaign-year argument that everything was going to hell and only he could fix it. During the first year of Trump, GDP growth grew to 2.4 percent, which is decent but not great and anyway, a reasonable person would acknowledge that — to the degree that economic performance is to the credit or blame of the president — the performance in the first year of a new president is a mixture of the old and new policies. In Trump’s second year, 2018, the GDP grew 2.9 percent, equaling Obama’s best year, and so far in 2019, the growth rate has fallen to 2.1 percent, a mediocre number and a decline for which Trump presumably accepts no responsibility and blames either Nancy Pelosi, Ilhan Omar or, if he can swing it, Barack Obama. I suppose it’s natural for a president to want to take credit for everything good that happens on his (or someday her) watch, but not the blame for anything bad. Trump is more blatant about this than most. If we judge by his bad but remarkably steady approval ratings (today, according to the average maintained by 538.com, it’s 41.9 approval/ 53.7 disapproval) the pretty-good economy is not winning him new supporters, nor is his constant exaggeration of his accomplishments costing him many old ones). I already offered it above, but the full Washington Post workup of these numbers, and commentary/explanation by economics correspondent Heather Long, are here. On a related matter, if you care about what used to be called fiscal conservatism, which is the belief that federal debt and deficit matter, here’s a New York Times analysis, based on Congressional Budget Office data, suggesting that the annual budget deficit (that’s the amount the government borrows every year reflecting that amount by which federal spending exceeds revenues) which fell steadily during the Obama years, from a peak of $1.4 trillion at the beginning of the Obama administration, to $585 billion in 2016 (Obama’s last year in office), will be back up to $960 billion this fiscal year, and back over $1 trillion in 2020. (Here’s the New York Times piece detailing those numbers.) Trump is currently floating various tax cuts for the rich and the poor that will presumably worsen those projections, if passed. As the Times piece reported: