有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Dropwizard的不同状态下使用不同的模拟

我正在尝试使用运行Dropwizard的应用程序设置pact提供程序,但在为不同的状态使用不同的模拟时遇到问题。在Dropwizard中是否有类似于Spring的@MockBean的方法,或者其他方法来实现这一点

这是我的提供者类:

@RunWith(PactRunner.class)
@Provider("my-proxy")
@PactFolder("src/test/java/pact/pacts")
public class UserContractTest {

    private static final String CONFIG_PATH = ResourceHelpers.resourceFilePath("config.yml");
//    I want to do the commented out code in Dropwizard with Dropwizard equivalents
//    @MockBean
//    private MyClass myMockedClass;

    @ClassRule
    public static final DropwizardAppRule<MyAppConfiguration> RULE =
            new DropwizardAppRule<>(MyAppMock.class, CONFIG_PATH);

    @TestTarget
    public final Target target = new HttpTarget(RULE.getLocalPort());

    @State("default")
    public void toDefaultState(Map<String, String> params) {
        if(params.get("someState").equals("stateOne")) {
            // when(myMockedClass.someFunc()).thenReturn("someAnswerForStateOne");
        } else {
            // when(myMockedClass.someFunc()).thenReturn("someAnswerForAllOtherStates");
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    最后,我在请求参数上使用了argThat,以便能够在同一个方法上使用两个不同的方法模拟

    public class MyAppMock extends MyApp {
    
       @Override
       protected UserProvider getUserProvider(Config config) {
           var myServiceMock = mock(UserProvider.class);
    
           var userResponseType = new UserResponseType();
           var user = new User();
           user.setName("Lisa");
           user.setAge(30);
           userResponseType.setUser(user);
    
           doReturn(userResponseType)
                   .when(myServiceMock)
                   .createUser(argThat(createUserRequestType ->  createUserRequestType.getName().equals("Lisa")), any());
    
           var errorMessage = "Error";
           doThrow(new SomeException(errorMessage, SC_NOT_FOUND))
                   .when(myServiceMock)
                   .createPaymentOrder(argThat(createUserRequestType ->  createUserRequestType.getName().equals("John")), any());
    
           return myServiceMock;
       }
    }