2017-09-15 4 views
-1

내가 FooEntity을 테스트하기 위해 노력하고있어이비웃음 코드 첫 번째 엔티티 프레임 워크 엔티티

public class FooEntity 
    { 
     private BarEntity Bar; 

     public void DoSomething() 
     { 
      var result = Bar.DoSomethingElse(); 

      if (result) 
       DoThis(); 

      else 
       DoThat(); 

     } 

     private void DoThis() { } 

     private void DoThat() { } 
    } 

같은 클래스가 있다고 할 수 있습니다. 단위 테스트의 관점에서 BarEntity를 테스트하지 않기 때문에 BarEntity를 모의하고 테스트 결과를 제공하고 싶습니다.

내가 본 모조 프레임 워크는 모의 인터페이스를 필요로하는 것 같습니다. 마지막으로 확인한 Entity Framework에서 인터페이스를 탐색 속성으로 사용하는 것은 지원되지 않습니다. 나는 인터페이스 형식의 엔티티에 맵핑되지 않은 속성을 추가하여 사용할 수 있습니다. 그것은 단지 약간의 테스트를 만족시키기 위해 그렇게하는 것이 다소 성가신 것 같습니다.

더 좋은 방법이 있습니까?

+1

Foo가 EF 엔티티 인 경우 간단하게 유지합니다. 방법이 없습니다. – mayu

+0

바를 어떻게 설정합니까? – mayu

+0

@ mayu : 그게 내가 고군분투하는거야. 필자는 항상 필드, getter 및 setter로 구성된 엔티티 (Java)를 유지했지만 메소드는 제공하지 않았습니다. 저 패션에서 본 코드의 대부분은 도메인 모델이 없습니다. 엔터티의 속성을 조작하는 서비스 클래스가 있습니다. 별도의 도메인 모델에서 앞뒤로 매핑하지 않고 엔티티 자체에 일부 동작을 추가하려고했습니다. – int21h

답변

1
using Moq; 

public class FooEntity 
{ 
    //if Bar is a table, you should write like this: 
    public virtual BarEntity Bar {get;set;} 
    public int BarId {get;set;} 

    public void DoSomething() 
    { 
     var result = Bar.DoSomethingElse(); 

     if (result) 
      DoThis(); 
     else 
      DoThat(); 
    } 

    private void DoThis() { } 
    private void DoThat() { } 
} 

var mock = new Mock<BarEntity>(); 
//DoSomethingElse method should be virtual and BarEntity should not be sealed 
mock.Setup(x => x.DoSomethingElse()).Returns(true);//or false 
var target2test = new FooEntity { Bar = mock.Object }; 
//action: 
target2test.DoSomething();//will result to DoThis calling 
+0

고마워요. 저는 C#으로 들어가는 자바 녀석입니다. 모의하기 위해 속성이 가상적이어야한다는 것을 깨닫지 못했습니다. 다시 한번 감사드립니다. – int21h