【问题标题】:Testing Methods that create objects inside the method with Junit and Mockito使用 Junit 和 Mockito 在方法内部创建对象的测试方法
【发布时间】:2021-08-27 14:18:11
【问题描述】:

您好,我对使用 Junit 和 Mockito 进行单元测试还很陌生。我认为我对这些原则有相当合理的理解,但我似乎无法找到任何关于我具体尝试在线测试的解释。

我想测试一个方法,它调用几个其他方法(void 和 non-void),它还实例化方法体中的对象。很遗憾,我不能分享代码,因为它不是我的,但这是一个通用格式:

class classToTest {
     private final field_1;

     public void methodToTest( string id, List object_1, List object_2) {
          try {
               Map<SomeObject_1, SomeObject_2> sampleMap = new HashMap<>();
               method_1(object_1, object_2); //void function modifies object_2
               field_1.method_2(id, object_2);
               Map<SomObeject_1, List<object>> groupedList = groupList(object_2)
               //Then some stuff is added to the sampleMap
          }
          //catch would be here
}

目前我只关心测试method_1,我不能直接测试,因为它是一个私有方法,所以我必须通过这个父方法调用。我希望我可以更改代码,但我被要求保持不变并使用 Mockito 和 Junit 以这种方式进行测试。

我知道我需要模拟要测试的类的一个对象及其参数:

private classToTest classToTestObject;
@Mock private field_1 f1;

@Before
public void setup() {
     MockitoAnnotations.init.Mocks(this);
     classToTestObject = mock(classToTest.class, CALLS_REAL_METHODS);
}

但我不知道从哪里开始我的实际测试,因为我基本上可以只执行一个方法调用而忽略所有其余的。我不能不忽略其他对象和方法调用,因为如果处理不当,主方法会抛出异常。

非常感谢任何帮助和指导,很抱歉我无法分享代码。谢谢!

【问题讨论】:

  • 听起来您正在寻找 Powermock Whitebox。在 stackoverflow 之前的讨论中有很多例子。

标签: java unit-testing junit mockito


【解决方案1】:

目前我只关心测试method_1,无法直接测试,因为它是私有方法,所以我必须通过这个父方法调用。

根据您的评论和代码中的注释:

method_1(object_1, object_2); //void function modifies object_2

您将设置一个测试来验证object_2 的预期最终状态。您将使用该类的真实实例而不是模拟来执行此操作。

@Test
public void method1Test() {
    // Assemble - your preconditions
    ClassToTest subject = new ClassToTest();
    List<SomeType> object_1 = new ArrayList();
    List<SomeOtherType> object_2 = new ArrayList();

    // Populate object_1 and object_2 with data to use as input
    // that won't throw exceptions. Call any methods on subject that put
    // it in the desired state

    // Act - call the method that calls the method under test
    subject.methodToTest("some id that makes the method run correctly", object_1, object_2);

    // Assert - one or more assertions against the expected final state of object_2
    assertThat(object_2).matchesYourExpectations();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多