简体   繁体   English

如何使用 Mockito 在另一个类中模拟依赖项

[英]How to mock dependecies in another class with Mockito

I am trying to do a JUnit Test.我正在尝试进行 JUnit 测试。 When I do this I get a NullpointerException.当我这样做时,我得到一个 NullpointerException。 Can I solve this problem using Mockito and if so, how?我可以使用 Mockito 解决这个问题吗?如果可以,如何解决?

@Test
public void test() throws Exception {

    Class1 class1 = new Class1(100, "TE", "TEST");
    
    Class2 class2 = new Class2();
    
    //I'm mapping class1 to class3 using class2.map, the usecase here is irrelevant for the problem
    Mapped<Class3> result = class2.map(class1, Class3.class);
    
}

Class2 looks something like this: Class2 看起来像这样:

public Class class2{
   @Inject
   private EntityMapper entityMapper; //entityMapper: null

   public Mapped<T> map(Class1 class1, Class<T> class3){
      return this.entityMapper.map(class1, class3);
   }
}

When I'm trying to execute my JUnit test, I get a NullpointerException because the entityMapper inside Class class2 is null.当我尝试执行 JUnit 测试时,我收到 NullpointerException,因为 Class2 中的 entityMapper 为空。 So I want to mock the EntityMapper using the Mockito framework but I can't get around this Problem.所以我想使用 Mockito 框架来模拟 EntityMapper,但我无法解决这个问题。

Your class2 is currently not properly unit testable.您的 class2 目前无法正确进行单元测试。 To make it testable, you need to use constructor/method injections so that we can mock and provide dependencies through test cases.为了使其可测试,您需要使用构造函数/方法注入,以便我们可以通过测试用例模拟和提供依赖项。 See below,见下文,

public class Class2{
   
   private EntityMapper entityMapper;

   @Inject
   public Class2(EntityMapper mapper){
       entityMapper = mapper;
   }

   public Mapped<T> map(Class1 class1, Class<T> class3){
      return this.entityMapper.map(class1, class3);
   }
}

Then through your test case you can mock and set dependencies as below,然后通过您的测试用例,您可以模拟和设置依赖项,如下所示,

@Test
public void test() throws Exception {
    EntityMapper mapper = mock(EntityMapper.class);
    Class1 class1 = new Class1(100, "TE", "TEST");
    Class2 class2 = new Class2(mapper);
    
   //TODO: Configure result of mocked functions using mockito when-then methods.
   Mapped<Class3> result = class2.map(class1, Class3.class);
    
}

Instead of creating Class2 class2 = new Class2();而不是创建Class2 class2 = new Class2(); in the test() , you can just usetest()中,您可以使用

@Mock
private Class2 class2;

at class level, and if it is a SpringBoot application you can try either @MockBean or @Mock在类级别,如果它是 SpringBoot 应用程序,您可以尝试@MockBean@Mock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM