如何在测试执行期间将参数值注入bean?

wqnecbli  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(323)

在一个 Car 我正在使用的类构造函数 @Value 将值作为参数注入的注解。

@Service
public class Car {

   public Car(@Value("${app.fabric.kafka.topics.sometopic}") final String topic) {
   }
   ...    
}
``` `GarageService` 类声明和使用 `Car` 示例。

@Component
@AllArgsConstructor
public class GarageService {

private @NonNull final Car; 

...
}

在一个 `GarageServiceTest` i类使用 `@InjectMock` 示例化测试对象 `@Mock` 注入另一个示例。

@ContextConfiguration
public class GarageServiceTest {
@Mock private CarService carService;
@InjectMock private GarageService;
...
}

这个类中的测试给出了一个异常:

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error when creating bean 'GarageService' defined in file [.../GarageService.class]:
Unsatisfied dependency expressed through constructor parameter 1,
...
nested exception is org.springframework.beans.factory.BenCreationException:
Error creating bean with name 'Car' defined in file [.../Car.class]: Unexpected exception during bean
creation; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder
app.fabric.kafka.topics.sometopic' in value "${app.fabric.kafka.topics.sometopic}".

问题是如何解决这个例外?我的理解是,在那个测试类中,我需要找到一种注入的方法 `${app.fabric.kafka.topics.sometopic}"` 值转换为bean“car”。
iklwldmw

iklwldmw1#

我知道你在用Spring撑杆做测试。这意味着spring将初始化 ApplicationContext 为了你的测试。显然,在初始化过程中 app.fabric.kafka.topics.sometopic 由于某些原因不可用。
这个初始化与mockito的无关 @Mock / @InjectMocks 注解。如果你想测试 GarageService Spring Bean CarService 被嘲笑时,请尝试以下操作:

public class GarageServiceTest {
    @MockBean private CarService carService; 
    @Autowired private GarageService;
    ...
}

如果你想要一个单元测试,在 GarageService 是作为常规对象创建的,只是不要使用 @RunWih(SpringRunner.class) / @ExtendWith(SpringExtension.class) 为了这个特殊的测试。
如果您在其他测试中遇到相同的问题,其中 CarService 不应该被嘲笑,用 @TestPropertySource(properties = "app.fabric.kafka.topics.sometopic=<whatever works>") 或者 @SpringBootTest(properties = "app.fabric.kafka.topics.sometopic=<whatever works>") 如果使用Spring Boot。

oogrdqng

oogrdqng2#

如果您想避免巨大的spring上下文:

@Data
@AllArgsConstructor
class Car {
    @Value("${app.fabric.kafka.topics.sometopic}")
    private String topic;
}

@Data
@AllArgsConstructor
class GarageService {
    private final Car car;
}

@RunWith(MockitoJUnitRunner.class)
public class dd {
    String topic = "topic";
    @Mock Car car;
    @InjectMocks GarageService garageService;

    @Test
    public void test() {
        when(car.getTopic()).thenReturn(topic);
        System.out.println(car.getTopic()); // topic
    }
}

相关问题