How to correctly mock an ObjectMapper object

Akinn :

I'm having a hard time mocking a com.fasterxml.jackson.databind.ObjectMapper object. In particular this the class I wanna test:

@Service
public class ClassToBeTested {

    private final ObjectMapper mapper;

    public ClassToBeTested(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    public void publicMethod(messageDto dto) throws JsonProcessingException {
        try{
            privateMethod(dto, param, "other string");
        } catch(JsonProcessingException e){
           // do stuff
        }
    }


    private void privateMethod(Object dto, String param, String param2) {
        
        Map<String, Object> attributes = new HashMap<>();

        attributes.putAll(mapper.readValue(mapper.writeValueAsString(dto),
                    new TypeReference<Map<String, Object>>() {
                    }));

        attributes.put("level", "error");
        //other stuff
    }
}

While my test class is:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestContextConfiguration.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class ClassToBeTestedTest {

    @MockBean
    private ObjectMapper mapper;

    private ClassToBeTested classToBeTestedActor;

    @PostConstruct
    public void initMock() throws JsonProcessingException {
        when(mapper.writeValueAsString(any())).thenReturn(any());
        when(mapper.readValue(anyString(), Mockito.<TypeReference<Map<String, 
            Object>>>any())).thenReturn(new HashMap<>());
    }

    @Before
    public void setup() {
        classToBeTestedActor = new ClassToBeTested(mapper);
    }

    @Test
    public void shouldFailJsonParsing() throws JsonProcessingException {
        // Given
        final Dto dto = mock(Dto.class);

        // When
        when(mapper.writeValueAsString(any()))
                .thenThrow(JsonProcessingException.class);

        // Then
        Assertions.assertThrows(JsonProcessingException.class,
                () -> classToBeTestedActor.publicMethod(dto));
    }
}

The purpose is to trigger and test the JsonProcessingException. The test fails because of an InvalidUseOfMatchersException:

Invalid use of argument matchers!
2 matchers expected, 3 recorded:
-> at com.ocado.crm.service.ClassToBeTestedTest.initMock(ClassToBeTestedTest.java:47)
-> at com.ocado.crm.service.ClassToBeTestedTest.initMock(ClassToBeTestedTest.java:48)
-> at com.ocado.crm.service.ClassToBeTestedTest.initMock(ClassToBeTestedTest.java:48)

where line 46 and 47 respectively are:

when(mapper.writeValueAsString(any())).thenReturn(any());

when(mapper.readValue(anyString(), Mockito.<TypeReference<Map<String, Object>>>any()))
                .thenReturn(new HashMap<>());

which makes no sense to me since I think I didn't mixed matchers and raw values.
How can I mock the ObjectMapper object correctly so that I can test JsonProcessingException?

SKumar :

I don't see the reason behind writing a test which mocks Object Mapper to throw some exception and then test whether the exception was thrown or not. Instead the test should be for the custom logic which is developed by you. If you have a method like this -

public void publicMethod(messageDto dto)  {
    try{
        privateMethod(dto, param, "other string");
    } catch(JsonProcessingException e){
       // do stuff
       dto.setXXX("XXX"); // The test should be testing this
    }
}

So, the test should be testing whether the dto is set correctly.

@Test
public void shouldFailJsonParsing() throws JsonProcessingException {
        // Given
        final Dto dto = new Dto();

        // When
        when(mapper.writeValueAsString(any()))
                .thenThrow(JsonProcessingException.class);

        // Invoke the method to be tested
        classToBeTestedActor.publicMethod(dto);

        // Test whether expected mock methods are invoked
        verify(mapper, times(1)).writeValueAsString(any());
        verifyNoMoreInteractions(mapper);

        // Assert results
        Assert.assertEquals("XXX", dto.getXXX());
    }

I get your point and I kind of agree with that. I just want to understand why, even if I am forcing the mapper to throw that exception, I am unable to assert it

I think the reason for this is that the exception is catched by you. That is the reason, that exception isn't propagated to your test.

public void publicMethod(messageDto dto) throws JsonProcessingException {
        try{
            privateMethod(dto, param, "other string");
        } catch(JsonProcessingException e){
           // do stuff
        }
    }

Try changing this to -

public void publicMethod(messageDto dto) throws JsonProcessingException {
        privateMethod(dto, param, "other string");
        
    }

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

How to configure ObjectMapper for Quarkus REST Client

How do I parse a Mongodb's UUID object using jackson ObjectMapper?

How to correctly mock an ObjectMapper object

How to mock a Kotlin singleton object?

How to define object in array in Mongoose schema correctly with 2d geo index

How to correctly bind checkbox to the object list in thymeleaf?

How to serialize correctly? Ajax updates all instances of a django upvote button in a object forloop when pressed

How to mock NSDate in Swift?

How to correctly delete an object from an array by name?

How to correctly pass object by type from C# to VBScript?

How to mock mongoose?

How do I correctly iterate through an object in render?

Jackson ObjectMapper readValue() unrecognized field when parsing to Object

How Do I Correctly Set a getElementById Object?

Swift ObjectMapper: How to parse JSON with backslash

How to mock the window navigator object while unit testing angular code

How do I mock an object being returned from a parent object all on the same call

How to use a (smart) pointer to mocked object (in google mock)

How should I correctly use setState for the following object

How to mock object for @Autowired in junit 5 unit test?

Is the memoryview object used correctly in this snippet?

how to mock an object that is used inside the tested method?

How to Mock ProceedingJoinPoint

$window object not correctly injected

How to correctly update embedded object's field in mongodb?

Jackson objectMapper gives different object for same json

How to use correctly JSON.stringify with an PHP returned JS object

How to mock a ZipFile object in S3?

How to create mock object of classes without interface

TOP 一覧

  1. 1

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  2. 2

    Railsで宝石のレイアウトを使用するにはどうすればよいですか?

  3. 3

    Chromeウェブアプリのウェブビューの高さの問題

  4. 4

    Ansibleで複数行のシェルスクリプトを実行する方法

  5. 5

    アンドロイド9 - キーストア例外android.os.ServiceSpecificException

  6. 6

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  7. 7

    CSSのみを使用して三角形のアニメーションを作成する方法

  8. 8

    Google Playストア:アプリページにリーダーボードと実績のアイコン/バッジが表示されない

  9. 9

    GoDaddyでのCKEditorとKCfinderの画像プレビュー

  10. 10

    PyCharmリモートインタープリターはプロジェクトタブにサイトパッケージのコンテンツを表示しません

  11. 11

    Windows 7では、一部のプログラムは「ビジュアルテーマを無効にする」レジストリ設定を行いませんか?

  12. 12

    Get-ADGroupMember:このリクエストのサイズ制限を超えました

  13. 13

    Pyusb can't find a device while libusb can

  14. 14

    MySQLでJSON_LENGTHとJSON_EXTRACTを組み合わせる方法は?

  15. 15

    Postmanを使用してファイル付きの(ネストされた)jsonオブジェクトを送信する

  16. 16

    Swiftのブロックのパラメーターに関するドキュメントのマークアップ形式は何ですか?

  17. 17

    Reactでclsxを使用する方法

  18. 18

    追加後、ブートストラップマルチセレクトがテーブルで機能しない

  19. 19

    MongoDB Compass: How to select Distinct Values of a Field

  20. 20

    「埋め込みブラウザのOAuthログイン」を有効にしてコールバックURLを指定した後でも、Facebookのコールバックエラーが発生する

  21. 21

    複数行ヘッダーのJTableヘッダーテキストの折り返し(カスタムTableCellRenderer)

ホットタグ

アーカイブ