2017-01-27 6 views
-1

HI я пытаюсь разработать тестовые случаи с JUnit + Mockito и облицовочные вопрос в связи с этим ..Mockito тест не перекрыт вызов, внутренняя функция

Это метод, который я пытаюсь проверить

public Response create(Request request) 
     throws SQLException, InvalidSecretKeyException, UnsupportedEncodingException, GeneralSecurityException, 
     InvalidParametersException, InvalidAuthKeyException, ConstraintViolationExceptions, InvalidKeyHashException, InvalidApplicationKeyException { 
    User user = userService.validateAndReturnUserBy(request.headers("AuthKey")); 

    ApplicationWrapper applicationWrapper = JsonUtil.deSerialize(request.body(), ApplicationWrapper.class); 

    //System.out.println(applicationWrapper.getSecretKey()); 

    Application application=new Application(); 
    application.setKey(getApplicationKey(user.getUserName(), applicationWrapper.getType().getName(), applicationWrapper.getName())); 
    System.out.println("GEN KEY ::::" + getApplicationKey(user.getUserName(), applicationWrapper.getType().getName(), applicationWrapper.getName())); 
    application.setName(applicationWrapper.getName()); 
    application.setPackageName(applicationWrapper.getPackageName()); 
    application.setSendOTPInResponse(applicationWrapper.getSendOTPInResponse()); 
    application.setType(applicationWrapper.getType()); 

    application.setSignature(applicationWrapper.getSignature()); 
    application.setCreatedAt(getMysqlTimeStamp()); 
    application.setCreatedBy(user); 
    application.setUpdatedBy(user.getId()); 
    application.setOtpExpiry(applicationWrapper.getOtpExpiry()); 
    application.setOtpLength(applicationWrapper.getOtpLength()); 
    application.setRandomNumber(tempRandomNumber); 

    validator.validate(application); 
    applicationRepository.create(application); 
    System.out.println(applicationWrapper); 

    Application thisApp =applicationRepository.getBy(application); 
    List<String> secretKeys = applicationWrapper.getSecretKey(); 
    System.out.println("Application Service ::: \n"+thisApp); 
    insertApplicationSecretKeys(secretKeys,thisApp); 
    Map<String, String> responseBody = new HashMap<>(); 
    responseBody.put("application_key", application.getKey()); 
    responseBody.put("message", "Application created Successfully"); 

    return new Response("success", responseBody); 
} 

И это мой Mockito + JUnit Test случай

@Test 
    public void shouldCreate() throws SQLException, ResourceNotFoundException, InvalidSecretKeyException, 
      UnsupportedEncodingException, GeneralSecurityException, InvalidAuthKeyException, InvalidParametersException, ConstraintViolationExceptions, InvalidKeyHashException, SendGridException, InvalidApplicationKeyException { 

    when(request.headers("AuthKey")).thenReturn("some-auth-key"); 
    when(userService.validateAndReturnUserBy("some-auth-key")).thenReturn(user); 
    when(request.body()).thenReturn(JsonUtil.toJson(make(a(ApplicationWrapperMaker.ApplicationWrapper)))); 
    when(applicationTypeRepository.getByName("WEB")).thenReturn(make(a(ApplicationTypeMaker.ApplicationType))); 
    when(userRepository.getByAuthKey("some-auth-key")).thenReturn(user); 

    //doNothing().when(appService).insertApplicationSecretKeys(make(a(ApplicationSecretKeyMaker.ApplicationSecretKey)), make(a(Application))); 
    //doThrow(new RuntimeException("App created")).when(appService).insertApplicationSecretKeys(make(a(ApplicationSecretKeyMaker.ApplicationSecretKey)), make(a(Application))); 

    Response response = applicationService.create(request); 

    assertEquals("success", response.getStatus()); 
    assertNotNull(response.getBody()); 
    } 

Существует проблема, где insertApplicationSecretKeys (secretKeys, thisApp); Вызывается .. Поскольку созданный объект приложения является всего лишь макетным объектом, этот метод возвращает null, и в этой строке приходит исключение NullPointer.

this app variable is coming NULL. 

Помогите.

EDIT: ВОТ StackTrace И ВЫВОД

java.lang.NullPointerException 
    at com.sendotp.service.ApplicationService.insertApplicationSecretKeys(ApplicationService.java:297) 
    at com.sendotp.service.ApplicationService.create(ApplicationService.java:92) 
    at com.sendotp.service.ApplicationServiceTest.shouldCreate(ApplicationServiceTest.java:162) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239) 
    at org.junit.rules.RunRules.evaluate(RunRules.java:20) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) 
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) 
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) 
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) 

Выход ::

GEN KEY ::::AhLDuwI4x34cP6-pr3WJSKoHZ7ltat13CdAcWlkZ8DHyiIk9b8-606JJ9ZPPPbTRWdnU7bPQYp4jphpdfqFoOwHs0uEc0ewE2-MHe8Yyu0XxZZQ7nw7itYVTXNFPp-a2NFP8AZ89QIznIzGstVWyO7eL7DS_qmam8BUF5XHN-VA= 
ApplicationWrapper{name='someApplicationName', [email protected], packageName='some.package.name', otpExpiry=86400, senderId='somesenderId', otpLength=6, requestPerIp=100, key='null', createdBy=null, updatedBy=0, createdAt=null, updatedAt=null, randomNumber='null', secretKey=[121212, 32234324], signature='some-signature,#OTP', sendOTPInResponse=0} 
Application Service ::: 
null 
+0

Вы должны использовать шпион на тестируемом объекте и сообщить insertApplicationSecretKeys ничего не делать – JeanValjean

+0

, пожалуйста, проверьте 2 пронумерованных строки кодов в тестовых случаях. Правильно ли я – ambitiousdev111

+0

, но проблема возникает, когда метод создания получает вызов – ambitiousdev111

ответ

0

Ваш метод create делает слишком много.

Специально создающий объект Application объект может быть сделан за пределами метода. Создание объекта других классов, обеспечивающих бизнес-логику, не должно быть сделано в классе с использованием этой зависимости. Должна быть применена инверсия зависимостей.

Самый простой способ - передать объект Application в качестве параметра в метод (который затем будет переименован в configure). В этом случае вы можете заменить его макетом, на котором вы могли бы проверить ожидаемые вызовы методов.

Смежные вопросы