Open black-shunshengli opened 6 years ago
@Service public class MockService { public static String staticPublicMethod() { return "staticPublicMethod"; }
public String publicMethod() {
return "publicMethod";
}
private static String staticPrivateMethod() {
return "staticPrivateMethod";
}
private String privateMethod() {
return "privateMethod";
}
public String testPrivateMethod() {
return this.privateMethod();
}
public String teststaticPrivateMethod() {
return staticPrivateMethod();
}
public String throwException() {
String sss = "111";
try {
System.out.println();
} catch (Exception ex) {
return "eeee";
}
return sss;
}
}
测试类:
@RunWith(SpringRunner.class) @SpringBootTest @FixMethodOrder(MethodSorters.JVM) public class DemoApplicationTests { @Autowired private MockService mockService;
private String mockStr = "mock privateMethod";
private String notMockStr = "privateMethod";
@Test
public void testPrivateMethod() {
new MockUp<MockService>() {
@Mock
public String privateMethod() {
return "mock privateMethod";
}
};
String result = mockService.testPrivateMethod();
System.out.println(result);
Assert.assertTrue(result.equals(mockStr));
}
@Test
public void testPrivateMethod2() {
String result = mockService.testPrivateMethod();
System.out.println(result);
Assert.assertTrue(result.equals(notMockStr));
}
}
@black-shunshengli 你是希望有@Mock注解的privateMethod()这个方法只在testPrivateMethod() 测试方法中生效,在testPrivateMethod2()测试方法中不生效, 是这个意思吗?
是的
放在不同的测试方法中,不会相互影响的。
就用你的例子去跑,并没有相互影响
` public class MockServiceTest { private MockService mockService = new MockService(); private String mockStr = "mock privateMethod"; private String notMockStr = "privateMethod";
@Test
public void testPrivateMethod() {
new MockUp<MockService>() {
@Mock
public String privateMethod() {
return "mock privateMethod";
}
};
String result = mockService.testPrivateMethod();
System.out.println(result);
Assert.assertTrue(result.equals(mockStr));
}
@Test
public void testPrivateMethod2() {
String result = mockService.testPrivateMethod();
System.out.println(result);
Assert.assertTrue(result.equals(notMockStr));
}
}`
我要mock一个http请求,在一个测试类的一个case里面写了一次() {
@Mock
public ApiResponse postApiResponse(HttpUrl url, Object postParams,
TypeReference<ApiResponse> typeReference) {
return ApiResponse.ok(null);
}
};
结果发现,所有这个测试类里面的其他调用都被mock掉了,不同类的ok
请问,如何让这种http mock只生效一次
new MockUp