mockito Junit5和mocking,空对象

ny6fqffe  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(114)

当一个类扩展另一个类时,我试图测试它,这需要我定义一个隐式构造函数。

public class MyCustomHandler extends SomeHandler {

   @Autowired
   private Object1 object1;

   @Autowired
   private Object2 object2;

   public MyCustomHandler (String name, ServicesManager servicesManager,
        PrincipalFactory principalFactory, Integer order) {
      super(name, servicesManager, principalFactory, order);
   }

   public boolean doSomething () {
     object1.foo();  // <- object1 is null here when testing
   }

   //Some other override methods
}

//Test class
@ExtendWith(MockitoExtension.class)
class CustomAzureAuthenticationHandlerTest {

    @Mock
    Object1 object1 ;

    @Mock
    Object2 object2 ;

    @InjectMocks
    MyCustomHandler myCustomHandler;

   //Test methods
   @Test
   void doSomeTest() {
       when(object1.doSomething()).thenReturn(false);
       myCustomHandler.someMethod();
   }
 }

当我的真实的类中的一个方法被调用时,它正在调用object1.foo(),而object1null
我理解这可能是由于没有一个no-args/default构造函数,它使用了我被迫实现的隐式构造函数,这并没有创建我的模拟对象。我只是不知道该怎么办。

jm81lzqq

jm81lzqq1#

将基于构造函数的注入与基于字段的注入混合使用是很奇怪的。我建议将所有依赖项移到构造函数中。然后,您可以根据需要传递所有内容:

public class MyCustomHandler extends SomeHandler {
   private final Object1 object1;
   private final Object2 object2;

   public MyCustomHandler (
         final String name,
         final ServicesManager servicesManager,
         final PrincipalFactory principalFactory,
         final Integer order,
         final Object1 object1,
         final Object2 object2) {
      super(name, servicesManager, principalFactory, order);
      this.object1 = object1;
      this.object2 = object2;
   }

   public boolean doSomething () {
     object1.foo();  // <- object1 is null here when testing
   }

   //Some other override methods
}
6yt4nkrj

6yt4nkrj2#

为了解决这个问题,您可以使用@BeforeEach注解在每次测试之前手动示例化MyCustomerTools,并传入模拟对象。JUnit 5中的@BeforeEach注解允许您在每次测试之前运行一些初始化代码。

@ExtendWith(MockitoExtension.class)
class CustomAzureAuthenticationHandlerTest {

    @Mock
    Object1 object1;

    @Mock
    Object2 object2;

    MyCustomHandler myCustomHandler;

    @BeforeEach
    void setUp() {
        // Manually instantiate MyCustomHandler with mock dependencies
        myCustomHandler = new MyCustomHandler("name", mock(ServicesManager.class), mock(PrincipalFactory.class), 0);
        myCustomHandler.object1 = object1;
        myCustomHandler.object2 = object2;
    }

    @Test
    void doSomeTest() {
        when(object1.foo()).thenReturn(false);
        myCustomHandler.doSomething();
        // Add your assertions here
    }
}

相关问题