Why to use Mockito? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am new to Mockito and I have started to learn it. But I have some questions. Why do we need to use Mockito? As far as I know it is used to Mock(Create dummy object) and write the test cases before having actual running code. But, what if I want to test my already implemented code to check whether they are functioning properly or not. How would I test it using Mockito?
For instance, I have CRUD methods and I would like to test whether Create is functioning properly by actually inserting data in database using my Create method, similarly for others. Can we attain it using Mockito. If not, then do I need to write different testcases for them without using Mockito?

The Mock is used to each class or service you are using. The class under test should not be Mocked. Lets assume you are connecting to a remote service which is being built by one of your engineering team, and you are not familiar with its internal functionality but you know what requests and response it returns.
In that case, you can create a Mock of that Object, and defines it with set of responses returns in different situations. Each situation should get its own different test and for each response you should check separately the reaction of the code (you are working on).
Another great example is creating a limitation checks. Lets think of exception that might be thrown in some situations.
You can Mock the object that will throw the Exception which is simple(~2-3 line of test code if you are using Mock) and you can check how the code you have written reacts to that Exception. Without the Mock the throwing of an exception might be really complicated thing and not so easy to use if you are not familiar with the small details. And of course the Mock enables you to be on focus of the main functionality you are checking cause it make the checking time very very small. And that is a bless when time to market is a critical thing.

Related

Javafx - What would the common way be to pre-load external data from a databse? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am pretty new to Javafx so saying already sorry if this may be an obvious question. I am using a Main class to do some housekeeping and pre-load the content from two json files so that everytime the app needs to get data, it does not need to read the file. Seems to me being the most efficient way. Then whenever the business logic needs the data it can call the static list and it's right there. But it seems completely against the entire OOP paradigm and it is already giving me a headache when trying to mock this for testing. So what is the common way of doing it out there?
1) How to pre-load a database at the very start of the program without it being hard later to access?
2) How to stay OOP and make that pre-load object persistent over the entire run of the app?
The data in the json are strings that need to be compared against incoming data over TCP in real time. Thus the need to be efficient. Sorry if this has been answered already but I can't seem to find a fitting strategy or patters that will solve this.
public static List<DrefData> database;
public static List<LayoutData> layout;
public static void main(String[] args) {
Initialize.logReportLevel("trace");
// load databases
DrefDataIO io = new DrefDataIO();
LayoutDataIO lio = new LayoutDataIO();
database = io.loadDatabase();
layout = lio.loadLayoutDatabase();
// open main window
MainWindow.main(args);
}
}
What you are trying to implement is a simple cache, an in memory representation of your database which is fast to access:
You need to implement the Singleton Pattern. This will ensure you only have an instance of your database object accessible to everyone in the same context. This will make it way easier to access since you will have a single object dedicated for that instead of it being in the Main class.
Although this solves both of your problems, it violates the single responsibility principle and will still be tricky to mock since a singleton must have the constructor private so it is only called by a named constructor once (not a Java expert but look at PowerMock i think it allows it).
Also, do you change your json in runtime? or is it a read-only

Test an if condition with mockito [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code of the if statement:
if (reponse.getStatus() >= HttpServletResponse.SC_BAD_REQUEST) {
LOGGER.error("Erreur lors de l'enregistrement de la trace technique - {}", reponse.getStatusInfo().getReasonPhrase());
}
Basically testing always consists of two parts:
preparing some input, so that your production code under test takes a specific path
verifying that the expected "things" happened
First one is easy: you have to somehow make sure that the response object that your production code is dealing with has the required status. How you do that, very much depends on context.
For the second aspect, that is probably hard. You see, the only action taking place is a (probably static) call to that error() message. If that is the case, then your only way of testing this would be to use JMockit or PowerMock(ito), because those two frameworks allow you to verify static method calls.
So, the real answer is:
figure for yourself how you can gain control over that response object
buy into using one of these mocking frameworks (not recommended)
rework your code so that it becomes testable without adding that (imho really really bad) dependency towards PowerMock(ito).

How do you make changes in dynamic languages, and find all of the places that will be broken by that change? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am used to programming in static languages like Java, where changing the signature of a method will cause a compilation error for every line of code that calls the method I changed. This makes modifying large projects much more easy, because I can make a change, and then let the compiler tell me about all the places that I need to fix.
When dealing with a large project in a dynamic language like Python or Ruby, how do you make code changes, and still remain confident that you are not going to be surprised with a run-time error in production because of some scenario you forgot about?
I've seen my fair share of NullPointerExceptions and ArrayIndexOutOfBoundsExceptions in Java, so it's not like these things never happen in a static language, I would just think they happen a lot less.
Here are some ideas for providing some level of the protection that you are used to in Java:
As stated in a previous comment, you should definitely provide adequate unit and integration testing to prevent any issues during a refactor. Testing is even more important in a dynamic language than in a statically-typed language. You should check that values are properly passed and handled in each of your functions.
Use PyCharm and search for usages on a method prior to making the update. This is not full-proof, but does find a good amount of method usage to allow for an easier refactor.
Do a global find for the method name in your editor or search program of choice.
Provide exception handling in your functions for cases where the type is incorrect or a value is unset.
Handle args and kwargs passed into your function carefully. Perhaps provide an error or debug log if you receive an unexpected input.
Provide default values for undefined parameters to a function.
Here is an example of providing a default value for a parameter to ensure that it is defined and initialized to None (similar to null) in the function if it is not passed in with a value:
def my_function(my_parameter=None):
# Do something with my_parameter

Are you supposed to write javadoc after or before you start programming? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I think javadocs are beautiful. Clear descriptions for each method and class. Our tester can easily write unit-tests without repetitive explanations from programmers.
This is how we practice TDD at our start-up. We first sit and plan the application structure, and we start creating all the methods and classes (without programming), we add descriptions to the classes, constructors and methods with javadoc. We then ship this to our tester who write unit tests. When he is done, we start programming.
No one is actually complaining. Our tester is in love with javadoc and although he is a terrible programmer (that is why he became a tester), he can easily understand the javadoc and write junit-tests.
The thing is, most of us are newbies in a start-up. And I don't know if you are supposed to document all the classes and methods before we even start programming? My question to you more experienced programmers is: is this a good TDD approach?
TDD is useful, because it makes sure you do not miss any requirements. It ends up beings used as unit test cases, and while the programmer starts their work they need to make sure all the test cases are covered.
Testers write system & integration test cases.
coming to javadoc, ideally it should be a must. It removes code duplication/reusablity and also adds some value to system document.
Javadoc should describe the return type, input params and process being carried out within the method.

Unit testing subclasses which refer to each other [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In Java I have the abstract class Place, with two concrete subclasses Area and Level; a Level must have a parent Area. But in trying to make unit tests for Level, I don't want to have create a full-fledged instance of Area. I see two ways of dealing with this:
1) Create an interface IPlace, extended by interface IArea, which Place and Area implement. Then create a MockArea class which implements IArea, and pass that to Level when testing it.
2) Use a mocking framework which will automatically create mock objects for me.
Which way is better? Or is there a third way to do it?
You're not giving us the reason why you don't want to create a full-fledged Area, but lets assume it does something difficult to test, like connect to a DB or read a file or something. Those are dependencies that it has. Dependency Injection is the answer.
For example, let's say Area does this in its constructor:
public Area() {
//get db connection
//do something with db connection
}
Now when you create a Level, it'll connect to a DB. Here's how you'd rewrite the constructor to use Dependency Injection:
public Area(Connection con) {
//do something with db connection
}
Now, when you create a Level, you can give it a fake Connection and are able to test your Level.
Now you can use a mocking framework to make a fake Connection. I recommend Mockito.
As you've written it, I'd suggest using a mocking framework.
Dependency Injection is great. Using it lets your classes state in an obvious way what types of things they need to interact with. If done properly, the need for mocked objects is often unavoidable. Get used to working with a mocking framework. I like Mockito personally.

Categories

Resources