I'm a bit confused on how to properly write unit tests for my application.
Actually i want to know if i have to rewrite an existed method and modify it for junit or just call my existed method and use assert.
So far, i use the second option, but i've came across with a problem.
For example, inside a Controller method i'm getting the currently logged in user and pass it to some services. If i call this method through JUnit it will show null exception because there is no logged in user.
So,
1) do i have to rewrite these kind of methods for testing purposes?
2) Is it proper to call existed methods and use assertion anyway?
Thanks
#RequestMapping(value="/like", method=RequestMethod.GET)
public String msgLike(#RequestParam("msgId") long messageId, #RequestParam("like") boolean like){
User user = new User();
user = this.userService.getUserByName(this.userService.getLoggedInUsername()); //NULL EXCEPTION HERE WHEN TESTING
if(!messageService.checkIfLiked(user, messageId)){
if(like){
messageService.insertLike(messageId);
messageService.insertMessageUserLike(user, messageId);
}
if(!like){
messageService.insertDislike(messageId);
messageService.insertMessageUserLike(user, messageId);
}
}
return "redirect:/home";
}
Actually i want to know if i have to rewrite an existed method and modify it for junit or just call my existed method and use assert.
Just call your exiting method, In fact junit is written before writing logic for calling method.
Example:
If you want to test int square(int num) method, which find square of given num,
So write Junits like this ,
#Test
squareTest() {
int square = objectName.square(3);
assertThat(square , is(equalTo(9)));
}
And when coding done like this,
int square(int a) {
result=a*a;
return result;
}
Run your Junit.
For your second question,
You will have to read Mocking.
In your case you are trying to test a rest controller which is slightly different when testing normal methods. For example the following method:
public MyClass{
public static int sum(int a, int b){
return a + b;
}
}
Could simply be tested by:
#Test
public void testSum(){
assertEquals(3, MyClass.sum(1, 2));
}
But in your case you require the controller api to be used properly. i.e. you require a logged in user. For this you would need to test your controllers by accessing them as users would. This provides some explanation on the process and this answer provides even more details.
Essentially what you are looking for is unit testing rest controllers.
What you need to do is in testing, supply a fake userService that will give the function a User with properties relevant for that test.
Before the test, you need to set this.userService to your FakeUserService.
It's hard to be more specific without seeing more of your code.
This is a good question because this is a common problem when learning to write unit tests. Solving this problem will help you write better code.
Related
I have the following method and I wrote a unit test in Java for this method. It is coveraged except from the if statement and I also need to test this part.
#InjectMocks
private ProductServiceImpl productService;
public void demoMethod(final List<UUID> productUuidList) {
if (productUuidList.isEmpty()) {
return;
}
final Map<ProductRequest, PriceOverride> requestMap = getPriceRequests(uuidList);
productService.updateByPriceList(priceRequestMap, companyUuid);
}
However, as the method execution is finalized and does not return anything when uuidList is empty, I cannot test this if block.
So:
How can I test this if block?
Should I create a new Unit Test method for testing this if block? Or should I add related assert lines to the current test method?
Update: Here is my test method:
#Test
public void testDemoMethod() {
final UUID uuid = UUID.randomUUID();
final List<Price> priceList = new ArrayList<>();
final Price price = new Price();
price.setUuid(uuid);
priceList.add(price);
productService.demoMethod(Collections.singletonList(uuid));
}
The general idea is that you don't want to test specific code, but you want to test some behaviour.
So in your case you want to verify that getPriceRequests and priceService.updateByPriceList are not called when passing in an empty List.
How exactly you do that depends on what tools you have available. The easiest way is if you already mock priceService: then just instruct your mocking liberary/framework to verify that updateByPriceList is never called.
The point of doing a return in your if condition is that the rest of the code is not executed. I.e., if this // code omitted for brevity was to be executed, the method would not fill it's purpose. Therefore, just make sure that whatever that code does, it was not done if your list is empty.
You have 3 choices:
Write a unit test with mocks. Mockito allows you to verify() whether some method was invoked.
Write a more high-level test with database. When testing Service Facade Layer this is usually a wiser choice. In this case you can obtain the resulting state of DB in your test to check whether it did what it had to.
Refactor your code to work differently
Check out Test Pyramid and How anemic architecture spoils your tests for more details.
Good afternoon,
i am having troubles with testing a boolean Method.
I have my interface (Dao)
public interface UserDao {
public boolean existUser(String email) throws UserException;
}
And my method is
public boolean existUser(String email) throws UserException {
try{
log.info("Verify exist email " + email);
Map<String, Object> parametersMap = Maps.newHashMap();
parametersMap.put("email", email);
Long count = npTemplate.queryForLong("SELECT count(*) FROM DL_USER WHERE EMAIL = :email", parametersMap);
if(count > 0){
return true;
}
}catch(Exception e){
String errorMsg = "There was an exception trying obtain user id for " + email + " - ERROR " + e.getMessage();
UserException uException = new UserException(errorMsg, e);
throw uException;
}
return false;
}
I would like to test the existUser method.
Create a set of test data comprising arguments to the method of which some should yield true, some false, and others the exception. Call the method with each value in turn and check the actual result with the expected result. Use a database with known content so you know what the expected values should be.
I prefer TestNG for this kind of testing.
Incidentally, the return false; should be inside the try block with the return true. Then you could eliminate the test of a boolean to return a boolean and simply return count > 0;.
There are basically two ways to test this kind of stuff:
a) As Lew already suggested, you could make this an integration test, which means you actually connect to the database, query the user, etc. If you want to be 100% sure, you can even create the user during test initialization and remove the user afterwards (for example by wrapping the whole test in a transaction and doing a rollback at the end). This will prevent your tests from depending on a specific database state or clutter the database with test data.
b) You could also make this a unit test via mocking. For this you would have to mock npTemplate, removing the need for an actual database connection. Then you can verify if npTemplate was called with the correct parameters. Also you can make it return various numbers to test different situations and even let it throw Exceptions to test that. Mockito is the to go framework for this kind of stuff, but there are others as well (for example EasyMock).
The obvious drawback to solution b) is, that you cannot guarantee that your query is actually correct, which doesn't leave much to test. Still, I personally would write both tests, a unit test and a integration test, since the unit test will ensure that the code around your query and the result handling is correct, while the integration test will ensure that your query actually works. (And yes, the integration test will also ensure that the code is correct, but running an integration test often takes far more time, so you can run your unit tests during development all the time and the integration tests only when needed).
And a little P.S., using...
return count > 0;
...will make your code more concise, since you will not have two different places where a return happens.
I want to test that a specific method produces the expected result, but to do that I need to manipulate the input in the test as well.
class ToTest {
public String produceResponse(String input) {
// ....
encryptedIds = encryptIds(input)
output = doStuff(input, encryptedIds)
}
public encryptIds(input) {
....
}
}
In my test I need to check that produceResponse actually produces the expected response.
in order to do that I have to encrypt the ids in the input.
My question is: should I rewrite encryptIds in the test (so that I would have more controller on the result) or should I call encryptIds from the class itself.
Is there a better approach to solve this? I don't like that in my test I know what happens in the specific flow.
If I understand correctly, you would like to test produceResponse() with known encryptedIds as input.
You could do that without refactoring the code, but it would probably be a good idea to refactor it, so that's what I'm going to explain:
class ToTest {
private IdEncryptor encryptor;
public ToTest(IdEncryptor encryptor) {
this.encryptor = encryptor;
}
public String produceResponse(String input) {
String[] encryptedIds = encryptor.encryptIds(input);
return doStuff(input, encryptedIds);
}
}
Now you can unit-test IdEncryptor to test that it produces correct encrypted IDs based on a String input.
And to test the ToTest class, you can mock the IdEncryptor so that whatever the input it receives, it produces the encryptedIds you desire. For example with mockito:
IdEncryptor mockEncryptor = mock(IdEncryptor.class);
when(mockEncryptor.encryptIds(any(String.class)).thenReturn(new String[] {"a", "b"});
ToTest toTest = new ToTest(mockEncryptor);
String response = toTest.produceResponse("input");
// expect that the response is what you expect given "a", "b" as input of doStuff()
Never copy any production code into the unit test as it will get outdated at some point.
If both methods are public, they are part of the public API, so:
you should first unit test the correct behavior of the encryptIds(String) method
then unit test the produceResponse(String) method which will internally use the already tested encryptIds(String) method
If encryptIds(String) would not be part of the public API:
then it is internal implementation and helper method which is not unit testable
produceResponse(String) is then responsible for encryption as a side-effect:
you can still test it if you mark it package private (no modifier)
you can also change the implementation of the encryptIds(String) only for testing purposes
Is encrypting id's something that is integral to your system or not? As it stands this class takes some input and produces some output and as far as your test is concerned this is what's important, no more, no less.
What is the impact of not performing the encryption? If your doStuff method will just fail if it doesn't happen then it is an internal detail to your class-under-test and I wouldn't have the tests care about it at all. If it's a step that absolutely must be performed then I would refactor the code to verify that it absolutely has happened, maybe using a mock as #jb-nizet answered.
As for the general case of duplicating production code in tests, as #Crazyjavahacking stated you should not do this, but I have no issue with using production code from a test- maybe not at a unit level but definitely the higher up the system I go, e.g. when testing writing to a DB I will use the reading code to verify it's happened correctly, but will also have independent tests to verify the reading path as well
I have a method which does following.
public void callService(SomeObject someObject) {
// call helper class method and create a request XML
// scrub this XML using a local method and persist it in MongoDB
// call a 3rd party service using HTTP POST
// Recieve the response
// Persist the response in MongoDB and set in in somObject
// return
}
Now as part of development we have to write unit test cases for this method. I am new to Junit testing as well as mock objects. but when I googled and looked at the some other similar questions I understood that testing void method is little bit different than normal methods and I think my above method which special in some more way as I am clueless as to what and how to test for this method.
Can someone please give me pointer or any reference as to how I can unit test this method using Junit.
You'd probably want to use mocks to stand in for your Mongo connection and the third party service. It's easiest to use an existing mock framework, but this is the general concept.
Pretend that you post to this third party service by constructing a StuffToPost object and passing it to the post method on your ThirdPartyPoster. Then you can create a mock object as follows:
public class MockThirdPartyPoster implements ThirdPartyPoster {
private int count = 0;
private StuffToPost stuffToPost;
#Override
public void post(StuffToPost stuffToPost) {
this.count++;
this.stuffToPost = stuffToPost;
}
public int getCount() {
return count;
}
public StuffToPost getStuffToPost() {
return stuffToPost;
}
}
In your test, you'd construct this MockThirdPartyPoster and pass it to thingToTest.setThirdPartyPoster, then call your method. Once the method finishes executing, you can call getCount() on the mock to make sure that you POSTed once and only once, and call getStuffToPost() to examine the StuffToPost object and make sure that it is correct. You'd do something similar for Mongo persistence as well.
That calls for a lot of boilerplate; mock frameworks like Mockito or EasyMock exist to solve that problem.
How can I test the following code?
class1 {
public InjectedClass injectedClass;
method1(){
returnValue = injectedClass.someMethod;
//another logic
}
method2(){
resultValue = method1();
}
}
My application was developed in Java. I use JUnit and Mockito.
To test method1() I can create a mock for InjectedClass and a mock logic for someMethod().
But how does one properly test a method? Do I need to create a mock for method1()?
UPDATE:
Let me demonstrate real example.
public class Application {
#Inject
DAOFacade facade;
//method1
public ReturnDTO getDTO(LiveServiceRequestParam requestParam) throws AffiliateIdentityException {
ReturnDTO returnDTO = new ReturnDTO();
CoreProductRepository repo = recognizeProduct(ProdCodeTypeEnum.MPN, null, vendorBound);
if(repo!=null){
//logic to fill some fileds in returnDTO
}
return returnDTO ;
}
//метод2
CoreProductRepository recognizeProduct(ProdCodeTypeEnum paramType, String prodCode, List<Integer> vendors) {
CoreProductRepository coreProductRepository = null;
switch (paramType) {
case MPN:
coreProductRepository = facade.findByAlternativeMPN(prodCode, vendors);
break;
case EAN:
coreProductRepository = facade.findByEan(prodCode, vendors);
break;
case DESCRIPTION:
coreProductRepository = facade.findByName(prodCode, vendors);
break;
}
return coreProductRepository;
}
}
So, to test recognizeProduct i mock DAOfacade. But also I want test getDTO method which uses recognizeProduct method.
You don't need to mock out your recognizeProduct method. As long as the DAOfacade is mocked, the behavior is known and deterministic, so the results of both getDTO and recognizeProduct can be verified.
It can also be argued, that you don't even need to test recognizeProduct specifically, because it is not public, so, there is no contract to enforce. As long as the behavior of getDTO is being tested and verified, your API is working as far as the user is concerned. The details of implementation aren't important.
In a way, testing recognizeProduct specifically is counter-productive, it hurts the maintainability and reliability of your code rather than helping it, because it makes any refactoring or reorganization harder to achieve even if it does not affect the externally visible behavior in any way.
If the methods are defined as shown in your example, they are package private. So, if you create a test in the same package (though normally in a test directory) you will be able to access those methods and test them.
That said, if you can refactor or rewrite the class to be more easily testable then that might be a good idea. If indeed you have to test the results of the internal methods and can't just test public ones.
You should focus your test effort on public methods return value and not not on internal implementation.
Focusing on internal implementation causes tests to be harder to mantain since a basic refactoring not affecting the return value will probably require changing your tests.
Sometimes is impossible to avoid testing internal implementation since some methods return nothing and you need to "assert" something. In this case it seems you return something at some point, I'd focus on testing that.
It seems to me you have a (sadly common) misunderstanding of the word test; it does not mean 'execute from a test case'.
Testing means supplying a range of inputs, and asserting that the corresponding outputs are correct. 99% of the time that means checking return codes or object state, occasionally you have to use mocks to properly test a pure-output interface.
If you do that for the public methods, and the private methods are fully covered to the required standard, job done. If there is uncovered code in private methods, either use it to identify and add a missing test case, or delete it.
In the event you feel there would be something useful lost by deleting unreachable private code, make it public, or move it out to another class.