RestTemplate Call with No Proxy [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have set proxy in my environment variables , however for a specific call made via RestTemplate , I shouldn't be using any proxy. Is there a way to disable proxy for a specific resttemplate call?

Instead of disabling and re-enabling the proxy, I'd use separate RestTemplates:
#Configuration
public class SomeConfig {
#Bean(name="proxyRestTemplate")
public RestTemplate proxyRestTemplate() {
// return a RestTemplate with proxy settings
}
#Bean(name="nonProxyRestTemplate")
public RestTemplate nonProxyRestTemplate() {
// return a RestTemplate without proxy settings
}
}
And in your classes:
#Component
public class SomeClassWithProxy {
private final RestTemplate restTemplate;
public SomeClass(#Qualifier("proxyRestTemplate") RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
#Component
public class SomeClassWithoutProxy {
private final RestTemplate restTemplate;
public SomeClass(#Qualifier("nonProxyRestTemplate") RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}

Related

How to mock interceptors? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 13 days ago.
The community is reviewing whether to reopen this question as of 13 days ago.
Improve this question
How to mock interceptor methods during test?
Example of class with interceptor:
#ApplicationScoped
public class MyServiceImpl implements MyService {
#Override
#MyAnnotation
public Uni<List<SomeDto>> getAll() {
return //
}
Example of interceptor which works via #MyAnnotation:
#Priority(100)
#MyAnnotation
#Interceptor
public class MyInterceptor {
#AroundInvoke
public Object someMethod(InvocationContext ic)throws Exception {
// some logic
return ic.proceed();
}
}
How test should be designed to mock invocation of someMethod in MyInterceptor?
#QuarkusTest
class SomeServiceTest {
#Test
void getAllNotBlacklisted() {
// ???
}

I keep getting 401 [No Body response] using RestTemplateBuilder

I have two RestTemplate Beans, however sometimes when authRestTemplate is used get a 401 error (org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]) I'm not sure why this is happening since it does not happen consistently.
This is how I have configured my RestTemplate.
#Configuration
#RequiredArgsConstructor
public class AppConfig {
private final FooConfig fooConfig;
#Bean
#LoadBalanced
public RestTemplate authRestTemplate(final RestTemplateBuilder restTemplateBuilder){
return restTemplateBuilder
.basicAuthentication(fooConfig.getUsername(), fooConfig.getPassword())
.build();
}
#Bean
#LoadBalanced
public RestTemplate basicRestTemplate(final RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.build();
}
}
If I am using the authRestTemplate it would look something like this
#Service
#RequiredArgsConstructor
public class authSubmissionServiceImpl implements CompletedApplicationService {
private final RestTemplate authRestTemplate;
private final FooConfig fooConfig;
#Override
public void doSomething() {
try {
Objects.requireNonNull(
authRestTemplate.getForObject(
String.format(somePath, fooConfig.getBaseUrl()),
String.class)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I use constructor injection and use the same variable name as the RestTemplkete bean to differentiate between the two. Because of this, I don't need to use #Qualifier(). However, I know the authentication is being sent because 99% of the time the request goes through fine but there are spontaneous times where I get 401 [No Body] and I'm stumped. Any help would be greatly appreciated

Should I write unit test for void methods (includes repository call)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I have the following code snippets in my spring boot application:
#Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
public UserServiceImpl(UserRepository ...) {...}
#Override
public void saveOrUpdateUser(UserDAO user) {
userRepository.save(user);
}
}
Test case class:
class UserServiceImplUnitTest {
private UserRepository userRepository = mock(UserRepository.class);
private UserService userService;
#BeforeEach
void setup() {
userService = new UserServiceImpl(userRepository);
}
}
I am using mockito to write my test cases. However, for this void method should i write test case(s)? If yes, how can i write it?
Yes. You should mainly focus on whether UserServiceImpl interacts with UserRepository in an expected way such as the things like if it invokes the correct method on the UserRepository with the correct arguments etc.
By using Mockito to mock the UserRepository , you may end up with a test something like as follows :
#ExtendWith(MockitoExtension.class)
public class UserServiceImplUnitTest {
#Mock
UserRepository userRepository ;
UserService userService;
#BeforeEach
void setup() {
userService = new UserServiceImpl(userRepository);
}
#Test
public void testSaveOrUpdateUser(){
UserDAO user = createDummyUser();
userService.saveOrUpdateUser(user);
verify(userRepository).save(same(user));
}
}

Spring-Boot RestClientTest not correctly auto-configuring MockRestServiceServer due to unbound RestTemplate

EDIT: This question is specifically pertaining to the #RestClientTest annotation introduced in spring-boot 1.4.0 which is intended to replace the factory method.
Problem:
According to the documentation the #RestClientTest should correctly configure a MockRestServiceServer to use when testing a REST client. However when running a test I am getting an IllegalStateException saying the MockServerRestTemplateCustomizer has not been bound to a RestTemplate.
Its worth noting that I'm using Gson for deserialization and not Jackson, hence the exclude.
Does anyone know how to correctly use this new annotation? I haven't found any examples that require more configuration then when I have already.
Configuration:
#SpringBootConfiguration
#ComponentScan
#EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class})
public class ClientConfiguration {
...
#Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.rootUri(rootUri)
.basicAuthorization(username, password);
}
}
Client:
#Service
public class ComponentsClientImpl implements ComponentsClient {
private RestTemplate restTemplate;
#Autowired
public ComponentsClientImpl(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
public ResponseDTO getComponentDetails(RequestDTO requestDTO) {
HttpEntity<RequestDTO> entity = new HttpEntity<>(requestDTO);
ResponseEntity<ResponseDTO> response =
restTemplate.postForEntity("/api", entity, ResponseDTO.class);
return response.getBody();
}
}
Test
#RunWith(SpringRunner.class)
#RestClientTest(ComponentsClientImpl.class)
public class ComponentsClientTest {
#Autowired
private ComponentsClient client;
#Autowired
private MockRestServiceServer server;
#Test
public void getComponentDetailsWhenResultIsSuccessShouldReturnComponentDetails() throws Exception {
server.expect(requestTo("/api"))
.andRespond(withSuccess(getResponseJson(), APPLICATION_JSON));
ResponseDTO response = client.getComponentDetails(requestDto);
ResponseDTO expected = responseFromJson(getResponseJson());
assertThat(response, is(expectedResponse));
}
}
And the Exception:
java.lang.IllegalStateException: Unable to use auto-configured MockRestServiceServer since MockServerRestTemplateCustomizer has not been bound to a RestTemplate
Answer:
As per the answer below there is no need to declare a RestTemplateBuilder bean into the context as it is already provided by the spring-boot auto-configuration.
If the project is a spring-boot application (it has #SpringBootApplication annotation) this will work as intended. In the above case however the project was a client-library and thus had no main application.
In order to ensure the RestTemplateBuilder was injected correctly in the main application context (the bean having been removed) the component scan needs a CUSTOM filter (the one used by #SpringBootApplication)
#ComponentScan(excludeFilters = {
#ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class)
})
The MockRestServiceServer instance should be constructed from the static factory, using a RestTemplate. See this article for a detailed description of the testing process.
In your example, you can do:
#RunWith(SpringRunner.class)
#RestClientTest(ComponentsClientImpl.class)
public class ComponentsClientTest {
#Autowired
private ComponentsClient client;
#Autowired
private RestTemplate template;
private MockRestServiceServer server;
#Before
public void setUp() {
server= MockRestServiceServer.createServer(restTemplate);
}
/*Do your test*/
}
You have RestTemplateBuilder at two places. At ClientConfiguration class and at ComponentsClientImpl class. Spring boot 1.4.0 auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. Remove below code from ClientConfiguration class and run your test.
#Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.rootUri(rootUri)
.basicAuthorization(username, password);
}

JUnit create dao fake object JAVA [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to test a class which is using dao. In my test class I have mocked the DAO and inject the mock into an instance of the class that I test. I am trying to make a fake object of the DAO class.
#RunWith(MockitoJUnitRunner.class)
public class UserManagerTest {
#Mock
private UserManagerDao umDao;
#InjectMocks
private UserManager um = new UserManager();
#Before
public void initializeMockito() {
MockitoAnnotations.initMocks(this);
}
public void testGetUserId() {
}
This here are the methods from UserManager.class and Dao class
userManager.class
public long getUserId(String email) throws Exception {
String[] partsOfMail = email.split("#");
return umDao.getUserId(partsOfMail[0], partsOfMail[1]);
}
Dao class
public long getUserId(String userName, String domain) throws Exception {
String sql = msa.getMessage("sql.select.user_id");
Object[] params = new Object[] { userName, domain };
List<Long> result = getJdbcTemplate().queryForList(sql, params, Long.class);
if (result.size() > 0) {
return result.get(0);
}
return 0;
}
See comments:
#RunWith(MockitoJUnitRunner.class)
public class UserManagerTest {
#Mock
private UserManagerDao umDao; // a mock object should present here
/* #InjectMocks should be able to create an instance
with mocks injected for you - you don't need to create it
yourself */
#InjectMocks
private UserManager um; // = new UserManager();
/* Not required as you're using the MockitoJUnitRunner
#Before
public void initializeMockito() {
MockitoAnnotations.initMocks(this);
} */
// Add test annotation (assuming JUnit4 as you're not extending TestCase)
#Test
public void testGetUserId() {
// Both these fields should not be null
Assert.assertNotNull(umDao);
Assert.assertNotNull(um);
}
For more information take a look at MockitoJUnitRunner and InjectMocks documentation.
Mockito's documentation, which included many examples, can be found here.
What is your question? If you are asking how to mock some method in the DAO, this is a simple example.
#Test
public void testGetUserId() {
when(umDao.getUserId(<PARS>)).thenReturn(1L);
assertThat(um.getUserId(<PAR>)).isEqualTo(1L);
}

Categories

Resources