2014-03-27 8 views
2

공동 작업자에게 메서드 호출을 받았을 때 Mockito가 특정 속성 만 올바르게 설정되어 있으면 확인을 받아 들일지 테스트하려고합니다. 그래서 논리적으로는 다음과 같습니다 시험Hamcrest hasProperty를 Specs2/Mockito와 함께 사용하십시오.

  • 클래스는 테스트중인 클래스는 새로운 객체를 구축
  • 가 전달 된 객체가 특정이있는 경우
  • Mockito이 전화를 확인
  • 가되었다 협력자에 전달할 인수와 협력자를 호출

    class ExampleSpec extends Specification with Mockito with Hamcrest { 
        val collaborator = mock[TargetObject] 
    
        "verifying a mock was called" should { 
         "match if a field on the called parameter was the same" in { 
         val cut = new ClassUnderTest(collaborator) 
         cut.execute(); 
         there was one(collaborator).call(anArgThat(hasProperty("first", CoreMatchers.equalTo("first")))) 
         } 
        } 
    } 
    

    W : 속성은 내가 지금까지 가지고하는 것은

코드 현명한 설정 여기에 정의 된 클래스는 다음과 같습니다

class ClassUnderTest(collaborator: TargetObject) { 
    def execute() = 
     collaborator.call(new FirstParameter("first", "second")) 
} 

class FirstParameter(val first: String, val second: String) { 

} 

trait TargetObject { 
    def call(parameters: FirstParameter) 
} 

바닐라 자바에서 나는 (위의 시도로) 중 하나 Hamcrest hasProperty의 정규으로이 작업을 수행하거나 내가 원하는 필드를 추출하기 위해 내 자신의 FeatureMatcher을 구현하는 것입니다. 위의 코드는 다음 오류와 함께 표시됩니다.

java.lang.Exception: The mock was not called as expected: 
Argument(s) are different! Wanted: 
targetObject.call(
    hasProperty("first", "first") 
); 
-> at example.ExampleSpec$$anonfun$1$$anonfun$apply$2$$anonfun$apply$1.apply$mcV$sp(ExampleSpec.scala:18) 
Actual invocation has different arguments: 
targetObject.call(
    FirstParameter(first,second) 
); 

진단 내용은 실제로 나에게별로 알려주지 않습니다. Hamcrest matchers로 원하는 방식으로, 또는 Specs2로 이상적으로 이상적으로이 작업을 수행 할 수있는 방법이 있습니까?

답변

1

관용적 방법은 FirstParameter 맞게 사용 matchA 위 코드에서 (specs2-matcher-extra 2.3.10에서)

import org.specs2.mock.Mockito 
import org.specs2.matcher._ 

class TestSpec extends org.specs2.mutable.Specification with Mockito with MatcherMacros { 
    val collaborator = mock[TargetObject] 

    "verifying a mock was called" should { 
    "match if a field on the called parameter was the same" in { 
     val cut = new ClassUnderTest(collaborator) 
     cut.execute 
     there was one(collaborator).call(matchA[FirstParameter].first("first")) 
    } 
    } 
} 

class ClassUnderTest(collaborator: TargetObject) { 
    def execute = collaborator.call(FirstParameter("first", "second")) 
} 

case class FirstParameter(first: String, second: String) 

trait TargetObject { 
    def call(parameters: FirstParameter) 
} 

MatcherMacros 특성을 사용하는 것 및 matchAfirst 방법은 FirstParameterfirst 값에 대응 수업. 이 예제에서는 예상 값을 전달하지만 다른 specs2 일치 자 (예 : startWith("f"))를 전달하거나 심지어 (s: String) => s must haveSize(5) 함수를 전달할 수도 있습니다.

+0

정말 대단한 감사합니다. 내 실제 데이터는 직선 값이 아닌 옵션을 사용합니다. 내가 그걸 어떻게 작동 시킬지 알고 있니? – tddmonkey

+0

'beSome (value)'또는 'beSome (startWith ("s"))'또는'beSome ((v : String) => v must haveSize (2))'또는'beNone'과 같은' – Eric