【问题标题】:Is it possible to postpone the initialization of the test subject until the test case with EasyMock?是否可以将测试主体的初始化推迟到使用 EasyMock 的测试用例?
【发布时间】:2017-08-30 13:19:39
【问题描述】:

是否可以初始化对象以不在声明时而是在每个测试用例中进行测试?我无法在声明时初始化对象,因为传递给构造函数的参数是测试用例的一部分。我需要一些东西:

  @TestSubject
  private ClassUnderTest classUnderTest;

  @Mock
  private Collaborator mock;

  @Test
  public void test12() {
    classUnderTest = new ClassUnderTest(1, 2);
    replay(mock);
    Integer result = classUnderTest.work(3, 4);
    // Assertions
  }

但如果我执行上述操作,Easymock 会抱怨:

java.lang.NullPointerException: Have you forgotten to instantiate classUnderTest?

我查看了MockBuilder,但我看不出它在这种情况下有何帮助。

【问题讨论】:

    标签: java unit-testing testing mocking easymock


    【解决方案1】:

    EasyMock 不支持您的要求。不过,其他测试库确实/可能支持它。例如,使用 JMockit:

    @Test
    public void test12(
        @Injectable("1") int a, @Injectable("2") int b, @Tested ClassUnderTest cut
    ) {
        Integer result = cut.work(3, 4);
        // Assertions
    }
    

    【讨论】:

      【解决方案2】:

      当然可以!有两种方法。

      在以前:

      private ClassUnderTest classUnderTest;
      
      private Collaborator mock;
      
      @Before
      public void before() {
        classUnderTest = new ClassUnderTest(1, 2);
        EasyMockSupport.injectMocks(this);
      }
      
      @Test
      public void test12() {
        classUnderTest = new ClassUnderTest(1, 2);
        replay(mock);
        Integer result = classUnderTest.work(3, 4);
        // Assertions
      }
      

      还是老办法:

      private ClassUnderTest classUnderTest;
      
      private Collaborator mock;
      
      @Test
      public void test12() {
        mock = mock(Collaborator.class);
        replay(mock);
      
        classUnderTest.setCollaborator(mock);
        classUnderTest = new ClassUnderTest(1, 2);
      
        Integer result = classUnderTest.work(3, 4);
        // Assertions
      }
      

      【讨论】:

      • 嗯,这是正确的,但问题似乎假设使用@TestSubject。未来版本的 EasyMock 可以增加对在测试方法中声明的“可注入”参数的支持,至少对于 JUnit 5(它有一个很好的 ParameterResolver)。
      猜你喜欢
      • 2019-11-08
      • 2023-04-03
      • 1970-01-01
      • 2015-12-03
      • 2013-04-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多